我经常写这样的代码:
answer.df = data.frame(x = numeric(0), y = numeric(0), z = numeric(0))
for (i in 1:100) {
x = do_stuff(i)
y = do_more_stuff(i)
z = yet_more_stuff(i)
# Is there a better way of doing this:
temp.df = data.frame(x = x, y = y, z = z)
answer.df = rbind(answer.df, temp.df)
}
我的问题是,在temp.df = data.frame(x = x, y = y, z = z)
行中,有更简洁的方法吗?想象一下有十个或更多变量来理解我的问题。
答案 0 :(得分:0)
试试这个:
do.call("rbind", lapply(1:100, function(i) list(x = xfun(i), y = yfun(i))))
还可以从data.table尝试rbindlist
,这可能会带来一些性能优势:
library(data.table)
rbindlist(lapply(1:100, function(i) list(x = xfun(i), y = yfun(i))))