Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 读取带单引号和双引号的字符串_R_String_Character - Fatal编程技术网

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

R 读取带单引号和双引号的字符串,r,string,character,R,String,Character,只是夏季对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 'singl

只是夏季对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
如果我们有一个巨大的文本文件(例如
.txt
),其中包含两种类型的引号,并且我们想在R中读取,该怎么办

在这一点上,对我来说一个(愚蠢的)解决方案似乎是:在R之外工作,做一些操作(比如用
\“
替换所有
),然后读入R。 这是一个解决方案还是R内部存在更好的方法

这里只是一个小小的
.txt
文件,例如:,不管对谁感兴趣,该文件只是一个
.txt
文件,其中有一行文字:

带单引号和双引号的字符串


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

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

readLines
的工作原理与tim的答案类似。或者,如果您觉得特别困难,您可以使用perl并环顾四周。或者,最好的答案是在导入R之前擦洗数据并删除引号。很抱歉,伙计们,添加文本文件时出现了延迟,dropbox出现了问题。现在该文件应该可用了。实际上,链接到Dropbox并不好,因为不是每个人都会安装它。请在问题本身中放置一个小版本的测试文件,而不是外部链接。
z1 <- "a string with 'single' quotes and with \"double\" quotes"
> 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?"
> 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?\""