开始使用免费开始使用

Replacing with backreferences

The replacement argument to str_replace() can also include backreferences. This works just like specifying patterns with backreferences, except the capture happens in the pattern argument, and the backreference is used in the replacement argument.

x <- c("hello", "sweet", "kitten")
str_replace(x, capture(ANY_CHAR), str_c(REF1, REF1))

capture(ANY_CHAR) will match the first character no matter what it is. Then the replacement str_c(REF1, REF1) combines the captured character with itself, in effect doubling the first letter of each string.

You are going to use this to create some alternative, more lively accident narratives.

The strategy you'll take is to match words ending in "ING" then replace them with an adverb followed by the original word.

本练习是课程的一部分

String Manipulation with stringr in R

查看课程

练习说明

  • Build a pattern that finds words that end in "ING". You'll want to check it against narratives using str_view().
  • Test out the replacement by using str_replace() with your pattern (don't forget to capture() it!) and a replacement str_c("CARELESSLY", REF1, sep = " ").
  • Build a vector with one adverb for each narrative by sampling 10 elements from adverbs.
  • Do the final replacement by using str_c(adverbs_10, REF1, sep = " ").

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Build pattern to match words ending in "ING"
pattern <- ___
str_view(narratives, pattern)

# Test replacement
str_replace(narratives, ___, ___)

# One adverb per narrative
adverbs_10 <- ___

# Replace "***ing" with "adverb ***ly"
___
编辑并运行代码