读取带有单引号和双引号的字符串

时间:2015-08-06 14:01:22

标签: r string character

夏天对R中字符串的好奇心。让我们说我有一个xy字符串。我们知道我们必须用双引号引用单引号,反之亦然。

x <- "a string with 'single' quotes"
y <- 'another one with "double" quotes'

paste0(x, y)
[1] "a string with 'single' quotesanother one with \"double\" quotes"
cat(x, y)
a string with 'single' quotes another one with "double" quotes

如果我们有一个带单引号和双引号的字符串怎么办?我试过这个: 反引号不起作用(R触发错误):

z <- `a string with 'single' quotes and with "double" quotes`

使用\"代替",然后使用cat: 这很有效,但问题是用户必须为每个双引号添加反斜杠。

z1 <- "a string with 'single' quotes and with \"double\" quotes"

如果我们有一个巨大的文本文件(例如.txt),但两种类型的引号并且我们想要读入R?

此时我的一个(愚蠢)解决方案似乎是:在R外工作,做一些操作(比如用"替换所有\")然后读入R. 这是一个解决方案还是在R内存在更好的方式?

以下只是一个小.txt文件:Link,无论如何感兴趣的人,该文件只是一个.txt,其中一行包含此文字:

  

带有“单引号”和“双引号”引号的字符串

1 个答案:

答案 0 :(得分:2)

您可以在阅读文本时根据需要指定任何备用引号,例如

> p<-scan(what="character",quote="`")
1: `It is 'ambiguous' if "this is a new 'string' or "nested" in the 'first'", isn't it?`
2: 
Read 1 item
> p
[1] "It is 'ambiguous' if \"this is a new 'string' or \"nested\" in the 'first'\", isn't it?"

或者,只需阅读原始文字,例如根据@rawr

的建议使用readline
> readline()
 "It is 'ambiguous' if "this is a new 'string' or "nested" in the 'first'", isn't it?"
[1] "\"It is 'ambiguous' if \"this is a new 'string' or \"nested\" in the 'first'\", isn't it?\""