How to replace (
, )
using sub in R ?
Let define x
as :
x="abc(def"
then when I try to replace (
by something else the error occur :
sub("(","",x)
the error is :
'Missing ')''
The sub() function in R is used to replace the string in a vector or a data frame with the input or the specified string. When you are dealing with large data sets, it's impossible to look at each line to find and replace the target words or strings. In this case, the sub() function will replace string.
Use str_replace_all() method of stringr package to replace multiple string values with another list of strings on a single column in R and update part of a string with another string.
Description Generalized "gsub" and associated functions. gsubfn is an R package used for string matching, substitution and parsing.
As Kohske said you need double escape, but you can also use the argument fixed=TRUE
:
sub("\\(","",x)
sub("(","",x,fixed=TRUE)
Both give you:
[1] "abcdef"
You need escape:
> sub("\\(", "@", x)
[1] "abc@def"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With