Search code examples
stringgrepeditgsub

R Replace word in a string


I have inherited an r project that has a dataframe with truncated text strings. Based on some responses in this forum, I have tried

temp$taname2 <- gsub("\bDistr\b", "District", temp$taname2)

This did not work. I tried

temp$taname2 <- gsub("Distr", "District", temp$taname2)

but this resulted in rows already containing the word "District" being changed to "Districtic", "Districtict", or similar. I also tried

temp$taname2[grep("\bDistr\b",temp$taname2)] <- "District"

but, alas, no luck.

I realise the answer is ridiculously simple but I haven't been able to work out how to do it.

Thanks in advance.


Solution

  • gsub("\\s+Distr$|^Distr\\s+|\\s+Distr\\s+|^Distr$", " District ", 
         c("ends with Distr", "distr at start", "the word distr in the middle", "distr", "district"),  ignore.case = T)