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.
This exercise is part of the course
String Manipulation with stringr in R
Exercise instructions
- Build a pattern that finds words that end in
"ING"
. You'll want to check it againstnarratives
usingstr_view()
. - Test out the replacement by using
str_replace()
with your pattern (don't forget tocapture()
it!) and a replacementstr_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 = " ")
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample 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"
___