1

I have these two lines of R codes:

df$symbol <- gsub("\\^", "-P", df$symbol)   # find "^" and change it to "-P"
df$symbol <- gsub("/", "-", df$symbol)      # find "/" and change it to "-"

How can I combine them into one line?

Thank you!

Steve
  • 193
  • 8
  • this might help https://www.rdocumentation.org/packages/textclean/versions/0.9.3/topics/mgsub – desval Mar 04 '21 at 07:46
  • Thanks! I tried qdap::mgsub() many times and received error message: could not find function "mgsub" – Steve Mar 04 '21 at 08:16
  • sorry, I referred to the "wrong" package. I wanted to point to `mgsub` from the `mgsub` package: https://cran.r-project.org/web/packages/mgsub/vignettes/Safe-Substitution.html – desval Mar 04 '21 at 08:52
  • I also tried mgsub::mgsub(), same error: could not find function "mgsub". My RStudio is quite stubborn. – Steve Mar 04 '21 at 09:11

1 Answers1

2

Given that you have two different replacement strings, there may not be a way to do this with just a single call to gsub. However, you could chain two calls to gsub here:

df$symbol <- gsub("/", "-", gsub("\\^", "-P", df$symbol))
Lennyy
  • 5,932
  • 2
  • 10
  • 23
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360