[R] putting output from print() into a string?

David Firth david.firth at nuffield.oxford.ac.uk
Sun Nov 12 19:25:26 CET 2000

>Uwe Ligges <ligges at statistik.uni-dortmund.de> writes:
> > On Sun, 12 Nov 2000, David Firth wrote:
> >
> > > Is there some neat way of storing the printed representation of an
> > > object as a character string?  I can see how it could be done via
> > > disk using sink() and then scan(), but that's ugly.
> > >
> > > Something like Lisp-Stat's "with-output-to-string" macro perhaps?
> >
> > dump() ?
>I don't think that was what David was looking for. If you really want
>to postprocess the printed output, the sink-then-scan method would
>seem to be the way to do it (or the soon-to- be readLines() instead of
>scan()). I suppose that a sink(text=...) could be implemented, but
>AFAIK it is not on anyones TODO list.

That's right, dump() doesn't do what I want: I should have made it 
clearer that what I would like to store in a string is the 
prettily-printed representation that gets displayed on the console 
when print() is called.  Yes, sink()-ing to a string would be nice. 
Or perhaps (more radically?) an optional argument as in print(mydata, 
return.the.string=TRUE) which requests the return of a string instead 
of returning the object mydata itself.

>One obvious counterquestion is "Why?". It would normally be preferable
>to retrieve information from the object itself rather than the printed
>representation, which is generally lossful in a number of ways.

I somehow thought I'd be asked this!  I need to exchange information 
rapidly with a non-R user using write.socket(), and for that purpose 
the information has to be in the form of a character string.  I can 
of course format the string myself using formatC(), paste(), etc., 
but it turns out that the way that data frames get formatted by 
print.matrix() is just right for my purposes.  So, rather than 
duplicate some of the excellent work that went into print.matrix(), 
I'd like to use it!

Thanks anyway for your very helpful answer, Peter: at least I can 
stop looking now.

Regards -- David

>   O__  ---- Peter Dalgaard             Blegdamsvej 3
>  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N
> (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
>~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
>r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
>Send "info", "help", or "[un]subscribe"
>(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list