1

I am trying to partially replace text within a string called "string1".

There are multiple patterns contained in "LocateMe" which I would like to look for and replace with the same string of text: "!= -9999"

The multiple patterns are quite complex containing special characters such as "=" and "["

Is it possible to achieve this using gsub or should I be using another function? Any guidance would be greatly appreciated.

string1 <- "Birth == unique.combos[17,1] & hid_age == unique.combos[17,2] & z02_gender == unique.combos[17,3]"

LocateMe <- c("== unique.combos[37,1]", "== unique.combos[38,1]", "== unique.combos[39,1]", "== unique.combos[40,1]", "== unique.combos[41,1]", "== unique.combos[42,1]",
                "== unique.combos[17,1]", "== unique.combos[17,3]", "== unique.combos[18,3]")


string2 <- gsub(LocateMe, "!= -9999", string1)
lmo
  • 37,904
  • 9
  • 56
  • 69
user104435
  • 11
  • 1
  • @Gregor - Thank you for the useful insight, I had not considered using a for loop opperation. I am still developing my R skills, for my current code this solution should be sufficient – user104435 Oct 09 '17 at 17:58

1 Answers1

1

gsub isn't vectorized over search strings, it only works with one at a time. So you'll need to use a loop like

string2 <- string1
for (i in seq_along(LocateMe)) {
  string2 <- gsub(LocateMe[i], "!= -9999", string2, fixed = TRUE)
}

Using fixed = T prevents those brackets, commas, and dots from being interpreted as special characters.

I'll also say that there is almost certainly a better way to do whatever you're trying to do in R than using gsub for find/replace, presumably followed by some eval(parse())ing. This will be painful to debug and difficult to scale.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294