Replacing the string + using gsub in R

40 views Asked by At

This is my df:

df <- data.frame(a = as.character(c("AB+CD+EF", "GH+IJ+KL")), x = c(1,2)
)
df
         a x
1 AB+CD+EF 1
2 GH+IJ+KL 2

When I replace the string "+" by ">" using gsub it places ">" between every string:

df$y <- gsub("+", ">", df$a)
df
         a x                 y
1 AB+CD+EF 1 >A>B>+>C>D>+>E>F>
2 GH+IJ+KL 2 >G>H>+>I>J>+>K>L>

Why does this happen?

Desired output:

         a x        y
1 AB+CD+EF 1 AB>CD>EF
2 GH+IJ+KL 2 GH>IJ>KL

Thanks

1

There are 1 answers

0
ThomasIsCoding On BEST ANSWER

You should enable fixed = TRUE

> transform(df, y = gsub("+", ">", a, fixed = TRUE))
         a x        y
1 AB+CD+EF 1 AB>CD>EF
2 GH+IJ+KL 2 GH>IJ>KL

or use chartr instead

> transform(df, y = chartr("+", ">", a))
         a x        y
1 AB+CD+EF 1 AB>CD>EF
2 GH+IJ+KL 2 GH>IJ>KL