-2

I am trying to correct a vector of strings with a for loop, this particular one is no working

gsub("S+U ", "t",  "S+U S+U lag") 

I also tried with grepl and it detects S+, +U, but with S+U does not work. Does someone know why does this happen?

2 Answers2

1

We can use fixed as TRUE as + is a metacharacter for one or more. So, in the regex mode, it will search for one or more 'S' followed by an U. Either use fixed = TRUE or escape (\\+) to evaluate literally

gsub("S+U ", "t",  "S+U S+U lag", fixed = TRUE) 
akrun
  • 874,273
  • 37
  • 540
  • 662
1

You should escape + by \\+

> gsub("S\\+U ", "t", "S+U S+U lag")
[1] "ttlag"

or you can enable fixed = TRUE

> gsub("S+U ", "t", "S+U S+U lag", fixed = TRUE)
[1] "ttlag"
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81