6

With R, when we put double quotes inside a double quotes:

y <- " " " "

It will end out

Error: unexpected string constant in "y <- " " " ""

My question is how to remove all the double quotes detected or convert into single quotes within the main double quotes.

For example:

y <- "I'm watching "Prometheus"." 
y

The desired result is

#[1] "I'm watching Prometheus."

or

#[1] "I'm watching 'Prometheus'."
Kai Feng Chew
  • 779
  • 8
  • 24

4 Answers4

5

Are you parsing string input from a file or standard input of something?

scan(what='character',sep='\n') will read data from the stdin() and automatically escape the quotes. Same if from a file

>scan(what="character",sep="\n",allowEscapes=T)
1: I'm watching "Prometheus"
2: 
Read 1 item
[1] "I'm watching \"Prometheus\""
>
>scan(what="character",sep="\n",allowEscapes=T)
1: "I'm watching "Prometheus""
2: 
Read 1 item
[1] "\"I'm watching \"Prometheus\"\""

Once you've got your input you could use a regular expression to replace the escaped inner quotes... (I think! - might be a complicated reg exp)

Davy Kavanagh
  • 4,809
  • 9
  • 35
  • 50
  • Thanks a lot. This is what I'm looking for! > y <- scan(what="character",sep="\n",allowEscapes=T) I'm watching "Prometheus". y – Kai Feng Chew Jun 20 '12 at 14:51
4

Im probably not getting it but

gsub("\"","","I'm watching \"Prometheus\".") 

or

gsub("\"","'","I'm watching \"Prometheus\".") 

?

shhhhimhuntingrabbits
  • 7,397
  • 2
  • 23
  • 23
1
y <-  "I\'m watching 'Prometheus'."

[1] "I'm watching 'Prometheus'."

y <-  "I\'m watching Prometheus."

[1] "I'm watching Prometheus."
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
DunderChief
  • 726
  • 4
  • 7
0

I used a combination of \ and single quotes around double quotes in a similar situation I had.

I wanted to pass the following string into a function as a test

"count(grepl("[()']", df$var)==T)>0"

but the [()'] became unquoted, the solution was

"count(grepl("'[()']'", df$var)==T)>0"