Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove single quote from a string in R?

Tags:

r

quotes

In a data frame I have text like

"X1" "X2"
"1" 53 "'[email protected]'"
"2" 54 "'[email protected]'"
"3" 55 "'[email protected]'"
"4" 56 "'[email protected]'"

How do I remove the single quotes from the string in 2nd column?

like image 432
phoenix Avatar asked Jul 20 '13 20:07

phoenix


People also ask

How do you remove quotes from a string?

Use the String. replaceAll() method to remove all double quotes from a string, e.g. str. replaceAll('"', '') . The replace() method will return a new string with all double quotes removed.

How do you ignore quotes in R?

noquote() function in R Language is used to prints strings without quotes.

How do I escape a single quote?

No escaping is used with single quotes. Use a double backslash as the escape character for backslash.

How do you replace quotes in R?

Just use "\"" or '"' to match a single double quote.


2 Answers

To replace text, use (g)sub:

result <- gsub("'", '', yourString)

The function is vectorised so you can apply it directly to your data frame without the need for a loop or an apply:

df$X2 <- gsub("'", '', df$X2)
like image 178
Konrad Rudolph Avatar answered Sep 25 '22 18:09

Konrad Rudolph


I know the question states otherwise, but what he actually wants to do is to unwrap this 2nd column, that is to remove tailing and leading single quotes. This can be done with a slightly enhanced regex:

gsub("(^')|('$)", "", df$X2)
like image 45
Holger Brandl Avatar answered Sep 22 '22 18:09

Holger Brandl