[R] write.csv to text string?

David Winsemius dwinsemius at comcast.net
Thu Mar 12 19:17:09 CET 2015


On Mar 12, 2015, at 10:15 AM, Thomas Nyberg wrote:

> Hello,
> 
> I've found the following useful functionality:
> 
>> s <- 'cola,colb\n1,2\n2,3\n'
>> read.csv(text=s)
>  cola colb
> 1    1    2
> 2    2    3
> 
> 
> But I haven't found a similar option in write.csv. I.e. I would like to
> "write" a dataframe to a string.

A data.frame is a list structure.

> What would be the easiest way to go
> about such a thing? Right now I can only think of using a file as an
> intermediary, but that seems a bit silly. Thanks for any help.

I think you are misunderstanding the structure of a computer file. `write.csv` is already doing essentially what you request. "Files" are essentially "strings" of varying sizes. The operating system print methods are displaying the linefeed/carriage in a manner that breaks the string into useful or readable segments on a "page".

If you want to have a text version of what the print.data.frame function returns, then wrap capture.output around print(dfrm). That will produce a character object.

--\n

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list