[R] Accumulating data row by row into a data frame

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Oct 12 11:24:39 CEST 2000


> Date: Thu, 12 Oct 2000 10:20:30 +0200 (METDST)
> From: Thomas Hoffmann <hoffmann at ehmgs2.et.tu-dresden.de>
> To: r-help at stat.math.ethz.ch
> Subject: [R] Accumulating data row by row into a data frame
> X-Keywords: 
> 
> After the overwhelming response to my last question (many thanks!),
> I cannot resist to ask the next maybe trivial question:
> 
> All sources I have looked into tell me about building data frames
> by reading from files or by putting vectors of data ("column by column")
> together.
> Now I would like to create an (empty) data frame with "headings" for
> every column (column titles) and then put data row-by-row into this
> data frame (one row for every computation I will be doing), i.e. I
> want to create kind of a "table" and fill it with data:
> 
> no. time temp pressure <---the headings
> 1   0     100   80     <---first result
> 2   10    110   87     <---2nd result .....
> 
> Is a data frame the best solution for this, anyway?

Depends if the cols are all numeric: if they are a matrix would be better.

If you know the number of results in advance, say, N, do this

df <- data.frame(time=numeric(N), temp=numeric(N), pressure=numeric(N))
df[1, ] <- c(0, 100, 80)
df[2, ] <- c(10, 110, 87)
...

or

m <- matrix(nrow=N, ncol=3)
colnames(m) <- c("time", "temp", "pressure")
m[1, ]  <- c(0, 100, 80)
m[2, ] <- c(10, 110, 87)

The matrix form is better size it only needs to access one vector
(a matrix is a vector with attributes) not three.

If you don't know the final size you can use rbind to add a row at a
time, but that is substantially less efficient as lots of re-allocation
is needed.  It's better to guess the size, fill in and then rbind on a lot
more rows if the guess was too small.

BTW, I left "no." off, as the rownames/row.names  serve that purpose.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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