0

I have a dataset with columns with names that include a string of special characters ("+/-"). I want to use gsub to replace this string with "plumin" but I can't figure out the regular expression to do it.

Example:

names(data) <- gsub("+/-", "plumin", names(data))
James Martherus
  • 1,033
  • 1
  • 9
  • 20

1 Answers1

2

We can place it inside square bracket to literally evaluate it otherwise the metacharacter meaning of + is one or more

names(data) <- gsub("[+/-]", "plumin", names(data))

If we want to replace the literal string, use fixed = TRUE as the default mode is regex and th characters (depends) would be evaluated accordingly

names(data) <- gsub("+/-", "plumin", names(data), fixed = TRUE)

The above will replace each of the +, / or - with "plumin".

But, if the intention is to replace those names with "plumin" having any of these substring, then use grep (not recommended to have duplicate names in the data)

replace(names(data), grep("[+/-]", names(data), "plumin")
akrun
  • 874,273
  • 37
  • 540
  • 662