MLEN
MLEN

Reputation: 2561

Using stringr::str_replace_all with character vector

str_replace_all from the stringr package lets you make multiple replacements by passing a named vector into the replacement= argument.

library(stringr)
charz <- data.frame(a = c('A', 'B'), stringsAsFactors = F)

# Works fine
str_replace_all('ABC', c('A' = '1', 'B' = 2))
[1] "12C" 

How can I do this with values from a data frame, rather than bare character vectors?

# Does not work
# Should return "12C" as above

str_replace_all('ABC', c(charz$a[1] = '1', charz$a[2] = 2)) 
Error: unexpected '=' in "str_replace_all('ABC', c(charz$a[1] ="

str_replace_all('ABC', c(charz$a[1], charz$a[2]), c('1', '2'))
[1] "1BC" "A2C"

Upvotes: 1

Views: 1199

Answers (1)

Phil
Phil

Reputation: 8107

From the help page for the function:

If you want to apply multiple patterns and replacements to the same string, pass a named vector to pattern.

I'm not sure why you can't refer to df$var to name a vector on the fly, but hopefully doing it prior to using str_replace_all() is workable in your case.

vec <- c("1", "2")
names(vec) <- charz$a

str_replace_all("ABC", vec)
> [1] "12C"

Upvotes: 3

Related Questions