[R] embedding data frame in R code?

William Dunlap wdunlap at tibco.com
Fri Aug 3 05:15:41 CEST 2012


> and you probably want closeAllConnections() immediately following

No you do not want to close all connections.  You should close each
connection that you open, but not others (they may be used by other
functions like sink() or capture.output()).  Use something like:

   readTableFromText <-function (text, ...) {
       tc <- textConnection(text, open = "r")
       on.exit(close(tc))
       read.table(tc, ...)
   }

as in

   > readTableFromText(c("10 ant", "20 bear", "30 cougar"), row.names=NULL)
     V1     V2
   1 10    ant
   2 20   bear
  3 30 cougar
  > showConnections() # no open connections
        description class mode text isopen can read can write
  >

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of R. Michael Weylandt
> Sent: Thursday, August 02, 2012 6:21 PM
> To: ivo welch
> Cc: r-help
> Subject: Re: [R] embedding data frame in R code?
> 
> I'm not sure I entirely understand the question, but the closest thing
> I can think of to a data frame literal, excepting dput(), would be
> this:
> 
> d <- read.csv(textConnection("
> a, b
> 1, cow
> 2, dog
> 3, cat"), header = TRUE)
> 
> and you probably want closeAllConnections() immediately following to
> avoid a warning.
> 
> Best,
> Michael
> 
> 
> On Thu, Aug 2, 2012 at 7:57 PM, ivo welch <ivo.welch at gmail.com> wrote:
> > I would like to insert a few modest size data frames directly into my
> > R code.  a short illustration example of what I want is
> >
> > d <- read.csv(  _END_, row.names=1  )
> >  , "col1", "col2"
> > "row1",1,2
> > "row2",3,4
> > __END__
> >
> > right now, the data sits in external files.  I could put each column
> > into its own vector and then combine into a data frame, but this seems
> > ugly.  is there a better way to embed data frames?  I searched for the
> > answer via google, but could not find it.  it wasn't obvious in the
> > data import/export guide.
> >
> > regards,
> >
> > /iaw
> > ----
> > Ivo Welch (ivo.welch at gmail.com)
> >
> > ______________________________________________
> > R-help at r-project.org mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list