R 附加数据帧而不重命名它的推荐做法? 背景
我正在编写一个不断更新数据帧的脚本:R 附加数据帧而不重命名它的推荐做法? 背景,r,coding-style,R,Coding Style,我正在编写一个不断更新数据帧的脚本: ## 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)) ##步骤A计算 结果在我的工作流程中,我创建了合并下来的列表。这里有一个例子 a &l
## 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))
##步骤A计算
结果在我的工作流程中,我创建了合并下来的列表。这里有一个例子
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
a添加它怎么样results=data.frame(A=results.from.A)
,results$B=results.from.B
,等等。对于我来说,像您在第一个示例中那样,将新数据帧绑定到现有数据帧并分配给现有数据帧似乎很好。我会这样做。将每个数据帧保存在一个列表中,并在最后将所有内容放在一起,就像您在上一个示例中所做的那样,看起来也不错。我两者都做,这取决于在上下文中哪种感觉更自然。@Benjamin您的方法绑定列而不是行,因此只能处理每个元素类型相同的向量,例如,不能混合使用字符和数字,例如c('a',1,2)
。我支持此工作流。使用do.call
和rbind
是一件很常见的事情,我想知道它是否应该成为一个单独的函数。@richicotton:rbind.list参见plyr::rbind.fill,它也比do.call+rbind快
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