Home > Back-end >  Is there any way to detect a specific word and replace a whole string with another in R language?
Is there any way to detect a specific word and replace a whole string with another in R language?

Time:11-23

I want to replace char value in R with another, it should be like this:

The key word to work is "Texas". And there is any way that I can do it with multiple files at once.

I have tried like this: df[df=="121 Texas"]<-"Texas" but it's clearly not smart at all when it comes to work with many dataframe at the same time.

CodePudding user response:

Let's say you had a dataframe with a column named "Original" and you wanted to replae all the entries in that column that contained the letters "Texas" as a substring with just the character value "Texas":

  df$Original[ grepl("Texas", df$Original) ] <- "Texas"

The grepl is one of the regex functions. It returns a logical value. The "[" function on the LHS of "<-" (technically the "[<-" function) can accept a logical index and only do the replacements for those items that register TRUE in the grepl test.

  •  Tags:  
  • r
  • Related