解决R中双引号内的双qoutes问题

时间:2012-06-20 10:11:45

标签: r

使用R,当我们在双引号内加双引号时:

y <- " " " "

它将结束

  

错误:“y&lt; - ”“”“”

中的意外字符串常量

我的问题是如何删除检测到的所有双引号或在主双引号中转换为单引号。

例如:

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

期望的结果是

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

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

3 个答案:

答案 0 :(得分:5)

您是从文件或标准输入中解析字符串输入吗?

scan(what='character',sep='\n')将从stdin()读取数据并自动转义引号。如果来自文件

,则相同
>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\"\""

获得输入后,您可以使用正则表达式替换转义的内部引号...(我认为! - 可能是一个复杂的reg exp)

答案 1 :(得分:4)

我可能没有得到它,但

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

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

答案 2 :(得分:1)

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

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

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

[1] "I'm watching Prometheus."
相关问题