mlinegar mlinegar - 23 days ago 9
R Question

Using group_by to replace different strings by group

I'm trying to replace every instance of an author's name in a data.frame with a different string, but only when that author was the one speaking. For instance, if we have the data:

test <- data.frame(author = c("jon", "mike", "sam"), text = rep("jon and mike mike and sam sam sam", 3))


I'd like to replace every instance of "sam" with some other text when
author=="sam"
.

I've tried using
do
and
str_replace_all
to do this, but haven't gotten it to work:

test %>% group_by(author) %>% do(mutate(., text2 = str_replace(.$text, eval(parse(text = .$author)), "yay")))

Answer Source

str_replace_all is Vectorised over string, pattern and replacement. (see ?str_replace_all), so you can just use the author column as pattern:

test %>% mutate(new_text = str_replace_all(text, author, 'yay'))

#  author                              text                          new_text
#1    jon jon and mike mike and sam sam sam yay and mike mike and sam sam sam
#2   mike jon and mike mike and sam sam sam   jon and yay yay and sam sam sam
#3    sam jon and mike mike and sam sam sam jon and mike mike and yay yay yay