R textConnection:“参数‘对象’必须解析为单个字符串”

sds*_*sds 5 r

我想将字符串列表转换为数据框。但是,我收到此错误:

> read.csv(textConnection(c("id,name,count",
                          '6289,aa,16',
                          '6269,bb,8',
                          '6269,cc,8',
                          '6269,dd,8',
                          '6610,ee,4')))
 Error in textConnection(c("id,name,count", "6289,aa,16", "6269,bb,8",  : 
  argument 'object' must deparse to a single character string
Calls: read.csv -> read.table -> textConnection
Run Code Online (Sandbox Code Playgroud)

当我只删除一行时,它会起作用:

> read.csv(textConnection(c("id,name,count",
                          '6289,aa,16',
                          '6269,bb,8',
                          '6269,cc,8',
                          '6610,ee,4')))
   id name count
1 6289   aa    16
2 6269   bb     8
3 6269   cc     8
4 6610   ee     4
Run Code Online (Sandbox Code Playgroud)

到底是怎么回事?!

pan*_*gia 8

阿难说得对,这种行为源自于deparse。在文档的“详细信息”部分下textConnection(),它说:

object应该是字符向量的名称:但是,只要它们解析到小于 60 个字节,短表达式就会被接受。

deparse()将表达式转换为字符串。当表达式解析超过 60 个字节时,deparse尝试将字符串拆分为更短的文本块;即字符串向量。尝试一下:

deparsed <- deparse(c("this expr","deparses to length=1,","nchar=57 bytes"))
deparsed
[1] "c(\"this expr\", \"deparses to length=1,\", \"nchar=57 bytes\")"
nchar(deparsed)
[1] 57

deparsed <- deparse(c("whereas this longer expression","deparses to length=2,","nchar=c(61,23) bytes"))
deparsed
[1] "c(\"whereas this longer expression\", \"deparses to length=2,\", "
[2] "\"nchar=c(61,23) bytes\")"
nchar(deparsed)
[1] 61 23
Run Code Online (Sandbox Code Playgroud)

这就是您收到错误的原因

argument 'object' must deparse to a single character string
Run Code Online (Sandbox Code Playgroud)

适合你较长的表达,但不适合你较短的表达。

正如 sds 和 Simon 各自所示,解决方案是将表达式分配给一个对象,然后对对象名称而不是原始表达式调用 textConnection。

txt <- c("id,name,count", '6289,aa,16', '6269,bb,8',
         '6269,cc,8', '6269,dd,8', '6610,ee,4')
read.csv(textConnection(txt))
    id name count
1 6289   aa    16
2 6269   bb     8
3 6269   cc     8
4 6269   dd     8
5 6610   ee     4
Run Code Online (Sandbox Code Playgroud)

在幕后,textConnection 现在正在调用deparse(substitute(txt))而不是deparse(substitute(c("id,name,count", ...))). 只有较短的表达式才会分解为单个字符串。这就是所textConnection需要的。