我想将字符串列表转换为数据框。 但是,我收到此错误:
> 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
当我只删除一行时,它会起作用:
> 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
这是怎么回事?!
最佳答案
阿南达说得对,这种行为源于deparse
。在 textConnection()
文档的“详细信息”部分下,显示:
object
should be the name of a character vector: however, short expressions will be accepted provided they deparse to less than 60 bytes.
deparse()
将表达式转换为字符串。当表达式 deparse 超过 60 个字节时,deparse 会尝试将字符串拆分为较短的文本 block ;即字符串向量。尝试一下:
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
这就是您收到错误的原因
argument 'object' must deparse to a single character string
适合较长的表达,但不适合较短的表达。
正如 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
在后台,textConnection 现在调用 deparse(substitute(txt))
而不是 deparse(substitute(c("id,name,count", ...)))
。只有较短的表达式才会分解为单个字符串。这就是 textConnection
所需要的。
关于R 文本连接 : "argument ' object' must deparse to a single character string",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21170633/