writing to a dataframe from a for-loop in R

前端 未结 4 570
遥遥无期
遥遥无期 2020-12-08 08:50

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

4条回答
  •  醉酒成梦
    2020-12-08 09:13

    If all your values have the same type and you know the number of rows, you can use a matrix in the following way (this will be very fast):

    d <- matrix(nrow=20, ncol=3) 
    for (i in 1:20) { d[i,] <- c(i+i, i*i, i/1)}
    

    If you need a data frame, you can use rbind (as another answer suggests), or functions from package plyr like this:

    library(plyr)
    ldply(1:20, function(i)c(i+i, i*i, i/1))
    

提交回复
热议问题