[R] write.csv to text string?

Thomas Nyberg tomuxiong at gmail.com
Thu Mar 12 20:12:39 CET 2015


I just wanted to send one final message out about this. My previous post
technically works, but is quite slow with large files/strings. I've
decided instead to do it exactly in the way that I was trying to avoid.
So just to set the record straight, these are the functions I'm going to
be using (the second two only so I can avoid a little extra thinking):

-------
write.csv.str <- function(df, row.names=F) {
    filepath <- tempfile()
    f <- file(filepath, "w")
    write.csv(df, f, row.names=row.names)
    close(f)

    s <- readfile(filepath)
    s
}


read.csv.str <- function(s) {
    read.csv(text=s)
}


readfile <- function(filepath) {
    text <- readChar(filepath, file.info(filepath)$size)
    text
}
-------

Thanks for the help everyone.

Cheers,
Thomas

On 03/12/2015 02:12 PM, John McKown wrote:
> On Thu, Mar 12, 2015 at 12:15 PM, Thomas Nyberg <tomuxiong at gmail.com> 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. 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.
>>
>> Cheers,
>> Thomas Nyberg
> 
> Perhaps something like:
> 
> textConn=textConnection("textCSV",open='w');
> write.csv(file=textConn,s)
> print(textCSV)
> 
> 
>



More information about the R-help mailing list