I want to turn a list of strings into a data frame. however, I get this error:
> 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
when I remove just one line, it works:
> 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
what is going on?!
Ananda has it right that the behavior originates in deparse
. Under the Details section of the textConnection()
documentation, it says,
object
should be the name of a character vector: however, short expressions will be accepted provided they deparse to less than 60 bytes.
deparse()
turns expressions into character strings. When an expression deparses to more than 60 bytes, deparse
tries to split the string into shorter text chunks; i.e., a vector of strings. Try it:
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
This is why you're getting the error
argument 'object' must deparse to a single character string
for your longer expression but not your shorter one.
The solution, as sds and Simon each showed, is to assign your expression to an object and then call textConnection on the object name rather than on the original expression.
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
Under the hood, textConnection is now calling deparse(substitute(txt))
rather than deparse(substitute(c("id,name,count", ...)))
. Only the shorter expression deparses to a single character string. And that's what textConnection
needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With