我对R语言中的字符串有些好奇。假设我有两个字符串x
和y
。我们知道在双引号中需要引用单引号,在单引号中需要引用双引号。
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 和前后查找。 - rawrexample.txt
文件到工作目录,但是使用download.file
我下载文件时遇到了问题,所以我决定添加文件链接。 - SabDeM