rdataframe

replace strings that contains one another


I have this problem

df<-data.frame(SS=c("New age, wow 20", "New age, wow" ))

I want to replace only "New age, wow" with "Yes" without affecting the first string. That is,

df_2<-data.frame(SS=c("New age, wow 20", "Yes" ))

I tried, as usual, using str_replace but it did not work.

str_replace(df$SS, "New age, wow", "Yes")

Note that my real vector contains thousands of such similar cases, so the order of the strings here is normally random


Solution

  • What about

    stringr::str_replace(df$SS, "^New age, wow$", "Yes")
    # [1] "New age, wow 20" "Yes"