[R] Writing list object to a file

Mike Prager mike.prager at noaa.gov
Wed Apr 23 15:59:55 CEST 2008


"Arun Kumar Saha" <arun.kumar.saha at gmail.com> wrote:

> Hi all,
> 
> I am wondering how to write a 'list' object to a file. I already gone
> through some threads like
> http://mail.python.org/pipermail/python-list/2001-April/080639.html, however
> could not trace out any reliable solution. I tried following :
> 
> > write.table(calc, file="c:/data.csv")
> Error in data.frame("200501" = c(-0.000387071806652095,
> -0.000387221689252648,  :
>   arguments imply differing number of rows: 25, 24, 16, 17, 18, 26, 27, 19,
> 23, 20, 11
> Anybody can help?

Remember that a list is not a rectangular table. It may have
components of various types and shapes. Therefore, it's unlikely
you'll be able to write a file that can be read easily by
another program.

That said, we do this occasionally for users who want to use
spreadsheets (yuck!) to analyze part of a list.  We use the
following function, which simply prints the list to an ASCII
file with a long line length:

##########################################
#  File:          Robj2txt.r
#  Language:      R
#  Programmer:    Michael H. Prager
#  Date:          July 7, 2004
#  Synopsis:
#  Function to write a complex R object to an ASCII file.
#  Main use is to write objects created from .rdat files;
#  however, could be used to save other objects as well.
#  This can be used to create files for those who want to use
#  a spreadsheet or other program on the data.
###########################################
Robj2txt <- function(x, file = paste(deparse(substitute(x)),
".txt", sep = "")) {
   #
   # ARGUMENTS:
   #  x:          R data object to save as ascii
   #  filename:   Name of file to save. Default is name of x
with ".txt" extension
   #
   tmp.wid = getOption("width")  # save current width
   options(width = 10000)        # increase output width
   sink(file)                    # redirect output to file
   print(x)                      # print the object
   sink()                        # cancel redirection
   options(width = tmp.wid)      # restore linewidth
   return(invisible(NULL))       # return (nothing) from
function
   }
##############################################

-- 
Mike Prager, NOAA, Beaufort, NC
* Opinions expressed are personal and not represented otherwise.
* Any use of tradenames does not constitute a NOAA endorsement.



More information about the R-help mailing list