remove parenthesis from string

2019-03-23 09:47发布

I am trying to remove a parenthesis from a string in R and run into the following error:

string <- "log(M)"
gsub("log", "", string) # Works just fine
gsub("log(", "", string) #breaks
# Error in gsub("log(", "", test) : 
#   invalid regular expression 'log(', reason 'Missing ')''

2条回答
Bombasti
2楼-- · 2019-03-23 10:08

Ben's answer gives you the good generally applicable way of doing this.

Alternatively, in your situation you could use the fixed=TRUE argument, like this:

gsub("log(", "", string, fixed=TRUE)
# [1] "M)"

It is appropriate whenever the pattern argument to gsub() is a character string containing the literal sequence of characters you are searching for. Then, it's nice because it allows you to type the exact pattern that you are searching for, without escapes etc.

查看更多
叼着烟拽天下
3楼-- · 2019-03-23 10:16

Escape the parenthesis with a double-backslash:

gsub("log\\(", "", string)

(Obligatory: http://xkcd.com/234/)

查看更多
登录 后发表回答