我正在尝试从循环写入R中的数据帧,例如像this>这样的循环
for (i in 1:20) {
print(c(i+i,i*i,i/1))}
并将每行3个值写入具有三列的数据帧,以便每次迭代都采用新的行。我尝试过使用矩阵、ncol=3和按行填充,但只从循环中获得了最后一项。
谢谢。
发布于 2010-04-01 22:14:55
您可以使用rbind:
d <- data.frame()
for (i in 1:20) {d <- rbind(d,c(i+i, i*i, i/1))}
发布于 2012-06-29 09:31:21
另一种方法是
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
如果不指定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
发布于 2010-04-01 22:17:33
For
循环有副作用,因此通常的做法是在循环之前创建一个空的dataframe,然后在每次迭代时添加到其中。您可以将其实例化为正确的大小,然后在每次迭代中将您的值分配给第i
行,或者添加到它并使用rbind()
重新分配整个内容。
前一种方法对于大型数据集将具有更好的性能。
https://stackoverflow.com/questions/2563824
复制