Remove parenthesis from a character string

mike picture mike · Feb 26, 2012 · Viewed 49.7k times · Source

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 ')''

Answer

Ben Bolker picture Ben Bolker · Feb 26, 2012

Escape the parenthesis with a double-backslash:

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

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