使用单引号和双引号读取一个字符串

3

我对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文件示例:链接,无论如何对于那些感兴趣的人,该文件只是一个包含此文本的一行.txt

a string with 'single' quotes and with \"double\" quotes


readLines 的工作方式类似于 Tim 的回答。或者,如果你感到特别困难,你可以使用 Perl 和前后查找。 - rawr
也许最好的答案是在导入R之前清洗数据并删除引号。 - Tim Biegeleisen
请在问题本身放置测试文件的小版本,而不是外部链接。 - A. Webb
@TimBiegeleisen 我觉得不需要安装Dropbox,只是一个指向服务器的外部链接。 - SabDeM
@A.Webb 我知道为了重现,最好创建一个脚本来复制并下载 example.txt 文件到工作目录,但是使用 download.file 我下载文件时遇到了问题,所以我决定添加文件链接。 - SabDeM
显示剩余2条评论
1个回答

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?\""

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接