1

Here Replace multiple strings in one gsub() or chartr() statement in R? it is explained to replace multiple strings of one character at in one statement with gsubfn(). E.g.:

x <- "doremi g-k"
gsubfn(".", list("-" = "_", " " = ""), x)
# "doremig_k"

I would however like to replace the string 'doremi' in the example with ''. This does not work:

x <- "doremi g-k"
gsubfn(".", list("-" = "_", "doremi" = ""), x)
# "doremi g_k"

I guess it is because of the fact that the string 'doremi' contains multiple characters and me using the metacharacter . in gsubfn. I have no idea what to replace it with - I must confess I find the use of metacharacters sometimes a bit difficult to udnerstand. Thus, is there a way for me to replace '-' and 'doremi' at once?

koteletje
  • 625
  • 6
  • 19

3 Answers3

4

You might be able to just use base R sub here:

x <- "doremi g-k"
result <- sub("doremi\\s+([^-]+)-([^-]+)", "\\1_\\2", x)
result

[1] "g_k"
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
3

Does this work for you?

gsubfn::gsubfn(pattern = "doremi|-", list("-" = "_", "doremi" = ""), x)
[1] " g_k"

The key is this search: "doremi|-" which tells to search for either "doremi" or "-". Use "|" as the or operator.

RLave
  • 8,144
  • 3
  • 21
  • 37
3

Just a more generic solution to @RLave's solution -

toreplace <- list("-" = "_", "doremi" = "")
gsubfn(paste(names(toreplace),collapse="|"), toreplace, x)
[1] " g_k"
Vivek Kalyanarangan
  • 8,951
  • 1
  • 23
  • 42