CommencerCommencer gratuitement

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.

Cet exercice fait partie du cours

String Manipulation with stringr in R

Afficher le cours

Instructions

  • 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 = " ").

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

# 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"
___
Modifier et exécuter le code