Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace '(' , ')' using sub in R?

Tags:

regex

r

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

like image 757
Qbik Avatar asked Apr 21 '12 12:04

Qbik


People also ask

What does sub () do in R?

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.

How do I replace multiple characters in a string in R?

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.

What package is GSUB in?

Description Generalized "gsub" and associated functions. gsubfn is an R package used for string matching, substitution and parsing.


2 Answers

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"
like image 130
Sacha Epskamp Avatar answered Sep 17 '22 18:09

Sacha Epskamp


You need escape:

> sub("\\(", "@", x)
[1] "abc@def"
like image 35
kohske Avatar answered Sep 18 '22 18:09

kohske