背景

我正在编写一个不断更新数据框的脚本:

 ## Step A calculations
 results <- data.frame(results.from.A)

 ## Step B calculations

 results <- rbind(results, results.from.B)

 ##At the end of script
 print(xtable(results))


但是,对现有对象名称results <- f(results的这种重新分配似乎是不好的做法。

我也可以这样做:

 ##At the end of script
 results <- as.data.frame(rbind(results.from.A, results.from.B))


或者只是添加到列表

 results <- list()

 ## Step A calculations
 results[[A]] <- results.from.A

 ## Step B calculations

 results[[B]] <- results.from.B

 ##At the end of script
 print(xtable(as.data.frame(results)))




这些或其他方法中的哪一种是首选?

最佳答案

在工作流程中,我创建要合并的列表。这是一个例子。

a <- 1:10
my.fun <- function(x) {
    data.frame(id = x, val = exp(x^2))
}

out <- lapply(X = as.list(a), FUN = my.fun)
class(out)
out <- do.call("rbind", out)

> out
   id          val
1   1 2.718282e+00
2   2 5.459815e+01
3   3 8.103084e+03
4   4 8.886111e+06
5   5 7.200490e+10
6   6 4.311232e+15
7   7 1.907347e+21
8   8 6.235149e+27
9   9 1.506097e+35
10 10 2.688117e+43


由您决定如何构造列表,甚至可以使用“常规”循环来完成。

附录

通常不建议增长对象(至少预先分配它)。您可以在R Inferno中阅读有关此内容的更多信息。

10-07 13:02