从R中的for循环写入数据帧

CCI*_*CID 16 for-loop r dataframe

我正在尝试从循环写入R中的数据帧,例如像这样的循环>

for (i in 1:20) {
print(c(i+i,i*i,i/1))}
Run Code Online (Sandbox Code Playgroud)

并将每行3个值写入具有三列的数据帧,以便每次迭代都采用新行.我尝试过使用矩阵,ncol = 3并按行填充,但只能从循环中获取最后一项.

谢谢.

Kar*_* W. 23

你可以使用rbind:

d <- data.frame()
for (i in 1:20) {d <- rbind(d,c(i+i, i*i, i/1))}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这可能是提议的效率最低的解决方案.对于非常小的数据集,它并不重要,但如果你想要有效,你真的不应该在循环中使用rbind或cbind. (3认同)

Rom*_*rik 10

另一种方式是

do.call("rbind", sapply(1:20, FUN = function(i) c(i+i,i*i,i/1), simplify = FALSE))


     [,1] [,2] [,3]
 [1,]    2    1    1
 [2,]    4    4    2
 [3,]    6    9    3
 [4,]    8   16    4
 [5,]   10   25    5
 [6,]   12   36    6
Run Code Online (Sandbox Code Playgroud)

如果未指定simplify = FALSE,则必须使用转置结果t.对于大型结构而言,这可能是乏味的.

如果你有一个较大的数据集和/或你需要多次重复这个解决方案,这个解决方案特别方便.

我在这个"线程"中提供了一些解决方案.

> system.time(do.call("rbind", sapply(1:20000, FUN = function(i) c(i+i,i*i,i/1), simplify = FALSE)))
   user  system elapsed 
   0.05    0.00    0.05 

> system.time(ldply(1:20000, function(i)c(i+i, i*i, i/1)))
   user  system elapsed 
   0.14    0.00    0.14 

> system.time({d <- matrix(nrow=20000, ncol=3) 
+ for (i in 1:20000) { d[i,] <- c(i+i, i*i, i/1)}})
   user  system elapsed 
   0.10    0.00    0.09 

> system.time(ldply(1:20000, function(i)c(i+i, i*i, i/1)))
   user  system elapsed 
  62.88    0.00   62.99 
Run Code Online (Sandbox Code Playgroud)


Sha*_*ane 6

For循环具有副作用,因此通常的做法是在循环之前创建一个空的数据帧,然后在每次迭代时将其添加到循环中。您可以将其实例化为正确的大小,然后i在每次迭代中将值分配给第'th行,或者添加到其中并使用来重新分配整个对象rbind()

对于大型数据集,前一种方法将具有更好的性能。


小智 6

如果您的所有值都具有相同的类型且您知道行数,则可以按以下方式使用矩阵(这将非常快):

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

如果你需要一个数据框,你可以使用rbind(作为另一个答案建议),或者像包plyr这样的函数:

library(plyr)
ldply(1:20, function(i)c(i+i, i*i, i/1))
Run Code Online (Sandbox Code Playgroud)