Re: [R] how to put the results of loop into a dataframe

From: Philipp Pagel <philipp.pagel.lists_at_t-online.de>
Date: Tue 20 Jun 2006 - 18:24:08 EST

On Tue, Jun 20, 2006 at 09:09:16AM +0800, zhijie zhang wrote:
> suppose i want to do the following caulation for 100 times, how to put the
> results of x , y and z into the same dataframe/dataset?
> x<-runif(1)
> y<-x+1
> z<-x+y

Several possibilities:

  1. Use rbind

Before loop:

d = NULL

And in the loop:

d = rbind(d, data.frame(x, y, z))

2) Build empty data frame of desired size beforehand and fill by row

E.g. for 10 rows:
d = data.frame( x=rep(0, 10), y=rep(0,10), z=rep(0,10))

And in the loop (index i):

d[i, ] = c(x, y, z)

3) Build vectors first, dataframe after the loop

x = NULL
y = NULL
z = NULL

in the loop:

x = append(x, runif(1))
...

After loop:

d = data.frame(x, y, z)

Solutions 1&3 are slower but you don't need to know the final number of rows in advance. Solution 2 is cleaner, in my opinion, but requires that you know the final size.

Of course, for the particular example calculation you don't need a loop at all:

x = runif(100)
y = x+1
z = x+y
d = data.frame(x,y,z)

cu
	Philipp

-- 
Dr. Philipp Pagel                            Tel.  +49-8161-71 2131
Dept. of Genome Oriented Bioinformatics      Fax.  +49-8161-71 2186
Technical University of Munich
Science Center Weihenstephan
85350 Freising, Germany

 and

Institute for Bioinformatics / MIPS          Tel.  +49-89-3187 3675
GSF - National Research Center               Fax.  +49-89-3187 3585
      for Environment and Health

Ingolstädter Landstrasse 1
85764 Neuherberg, Germany
http://mips.gsf.de/staff/pagel

R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Tue Jun 20 18:30:21 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 20 Jun 2006 - 20:11:12 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.