Re: [R] Escaping " ' " character

From: Marc Schwartz (via MN) <mschwartz_at_mn.rr.com>
Date: Tue 22 Aug 2006 - 07:51:53 EST

On Mon, 2006-08-21 at 13:43 -0700, Srinivas Iyyer wrote:
> Dear all:
>
> I have a character object x with ' (single-quote)
> character.
>
> x <- c('"hydrolase activity","actin
> binding","3',5'-cyclic-nucleotide phosphodiesterase
> activity")
>
> I want to write a function that will identify ' and
> replaces with \'
>
> myf <- function(term){
> if (grep("'",term))
> { sub("'","\'",term)}
> }
> > myf(x)
> [1] "hydrolase activity"
> [2] "actin binding"
> [3] "3',5'-cyclic-nucleotide phosphodiesterase
> activity"
>
>
> In the result "3',5'" is remains unchaned. I expected
> that to "3\',5\'-cyclic-nucleotide phosphodiesterase
> activity".
>
> Could any one help me here.
> Thank you.

<snip>

Srini,

Try this:

 x <- "3',5'-cyclic-nucleotide phosphodiesterase activity"

> x

[1] "3',5'-cyclic-nucleotide phosphodiesterase activity"

> gsub("'", "\\\\'", x)

[1] "3\\',5\\'-cyclic-nucleotide phosphodiesterase activity"

Note that I use gsub() to replace both instances of the ', whereas sub() will only replace the first.

The escape character itself needs to be escaped when used within the replacement regex, since the "\" is a metacharacter. You end up with four "\"s since R also treats the "\" specially.

When you cat() the output, you get:

> x.new

[1] "3\\',5\\'-cyclic-nucleotide phosphodiesterase activity"

> cat(x.new, "\n")

3\',5\'-cyclic-nucleotide phosphodiesterase activity

HTH, Marc Schwartz



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Tue Aug 22 08:02:46 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Wed 23 Aug 2006 - 02:21:41 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.