Home > database >  Replace first occurrence of word in a string with R program
Replace first occurrence of word in a string with R program

Time:07-01

Would like to replace first occurrence of CARS word with empty space, not replacing the middle and last occurrence

using gsub, it is replacing all the values in the column

CAR_ID <- c(5001,5002)
CAR_Details <- c(" CARS THIS CARS BUSINESS IS NOT JUST BUYING CARS", " CARS BUSINESS INVOLVES DEALING WITH OLD CARS AS WELL AS NEW CARS")

df1 <- data.frame(CAR_ID,CAR_Details)

df1$CAR_Details <- gsub("CARS",",df1$CAR_Details)

CodePudding user response:

Rather than using gsub, just use sub:

df1$CAR_Details <- sub("CARS", " ", df1$CAR_Details)

By the way, the g in gsub stands for "global," meaning it will replace everywhere. The sub() version will only replace the first match found, from left to right.

CodePudding user response:

stringr::str_replace will only replace the first occurrence.

str_replace(df1$CAR_Details, "CARS", " ")
[1] "   THIS CARS BUSINESS IS NOT JUST BUYING CARS"                  "   BUSINESS INVOLVES DEALING WITH OLD CARS AS WELL AS NEW CARS"

CodePudding user response:

Here are two solutions: First one is for the first question removing the first occurence of CARS. Note In the first solution everything before the first space will be removed, (extra Note: in row1 we have two space therefore trimws)

df1$CAR_Details <- sub('.*? ', '', trimws(df1$CAR_Details))

  CAR_ID                                                 CAR_Details
1   5001                  THIS CARS BUSINESS IS NOT JUST BUYING CARS
2   5002 BUSINESS INVOLVES DEALING WITH OLD CARS AS WELL AS NEW CARS

Second solution is the updated for removing the second occurence of CARS (see comments in Tim Biegelsen's answer:

df1$CAR_Details <- sub('(CARS.*?)CARS', '\\1', trimws(df1$CAR_Details))

  CAR_ID                                                  CAR_Details
1   5001                  CARS THIS  BUSINESS IS NOT JUST BUYING CARS
2   5002 CARS BUSINESS INVOLVES DEALING WITH OLD  AS WELL AS NEW CARS
  • Related