writing to a dataframe from a for-loop in R

前端 未结 4 565
遥遥无期
遥遥无期 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:04

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

提交回复
热议问题