views:

534

answers:

2

I'm trying to write from a loop to a data frame in R, for example a loop like this>

for (i in 1:20) {
print(c(i+i,i*i,i/1))}

and to write each line of 3 values to a data frame with three columns, so that each iteration takes on a new row. I've tried using matrix, with ncol=3 and filled by rows, but only get the last item from the loop.

Thanks.

+4  A: 

You could use rbind:

d <- data.frame()
for (i in 1:20) {d <- rbind(d,c(i+i, i*i, i/1))}
Karsten W.
+2  A: 

For loop have side-effects, so the usual way of doing this is to create an empty dataframe before the loop and then add to it on each iteration. You can instantiate it to the correct size and then assign your values to the i'th row on each iteration, or else add to it and reassign the whole thing using rbind().

The former approach will have better performance for large datasets.

Shane
Thanks for both these answers, to assign values to the ith row do you mean something like this, (this doesn't actually work). Also, would this way work with a dataframe with unknown no of rows? rm(d) d <- data.frame(nrow=20, ncol=3) for (i in 1:20) { d[i,] <- c(i+i, i*i, i/1)}
CCID
Why did you say "unknown no of rows" when your example has i in 1:20? If there are unknown number of rows, you'll need to use something like rbind as another answer suggests.
Apprentice Queue