Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R gsub a single double quotation mark

I have a field of strings in a data frame all similar to:

"Young Adult – 8-9"" 

where the inner single " is what I want to replace with nothing to get:

"Young Adult - 8-9"

How can I do this? I tried to escape with a double backslash:

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

but got this error: Error: unexpected string constant in "gsub("\"", ""

like image 651
Oliver Oliver Avatar asked May 17 '16 17:05

Oliver Oliver


People also ask

How do you use quotation marks on GSUB?

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

What is the difference between single and double quotes in R?

Single and double quotes delimit character constants. They can be used interchangeably but double quotes are preferred (and character constants are printed using double quotes), so single quotes are normally only used to delimit character constants containing double quotes.

How do you add double quotes in R?

dQuote in R The dQuote() is a built-in R function used to convert the given string or character vector into double quote text. It takes a specified string or character vector as an argument and returns the double-quoted text. To convert a string or character vector to double-quote text in R, use the dQuote() function.

Can you use single quotes in R?

The single quote version in R is for convenience. (Since) On most keyboards you don't need to use the shift key to type a single quote but you do need the shift for a double quote.


1 Answers

You do not need to escape a double quote in a regular expression. Just use "\"" or '"' to match a single double quote.

s = "Young Adult – 8-9\""
s
[1] "Young Adult – 8-9\""
gsub("\"", "", s)
[1] "Young Adult – 8-9"
gsub('"', "", s)
[1] "Young Adult – 8-9"

See this IDEONE demo

NOTE: Since you want to remove some literal text, you do not even need a regex, use fixed=TRUE argument to speed up the operation:

gsub('"', "", s, fixed=TRUE)
like image 161
Wiktor Stribiżew Avatar answered Oct 05 '22 12:10

Wiktor Stribiżew