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?

4

3 回答 3

4

您也许可以sub在这里使用base R:

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

[1] "g_k"
于 2019-01-03T10:42:48.797 回答
3

这对你有用吗?

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

关键是这个搜索:"doremi|-"它告诉搜索"doremi"or 或"-"。用作运算"|"or

于 2019-01-03T10:40:56.847 回答
3

只是@RLave 解决方案的一个更通用的解决方案 -

toreplace <- list("-" = "_", "doremi" = "")
gsubfn(paste(names(toreplace),collapse="|"), toreplace, x)
[1] " g_k"
于 2019-01-03T10:45:55.653 回答