[R] embedding data frame in R code?

Gabor Grothendieck ggrothendieck at gmail.com
Fri Aug 3 05:36:17 CEST 2012


On Thu, Aug 2, 2012 at 8: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.
>

This is only a small variation on what others have already proposed
but using text= has the advantage over using an explicit
textConnection that the closing of the connection is handled for you
and separating the data and the read.csv code has the advantage that
if you want to re-read it then its easy to repeat the single read.csv
line.  This latter point is particularly helpful if you are
interactively working with it but even if not it looks better IMHO
than squishing the data within the read.csv .

Lines <- ' "col1","col2"
"row1",1,2
"row2",3,4 '

DF <- read.csv(text = Lines)

Actually if the data frame is small enough the compactness of the
following may outweigh any trepidation you have:

DF <- data.frame(col1 = c(1, 3), col2 = c(2, 4), row.names = c("row1", "row2"))


-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list