在 for 循环中将数据帧附加在一起 [英] Append data frames together in a for loop
本文介绍了在 for 循环中将数据帧附加在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 for 循环
,它在每次迭代后生成一个数据帧.我想将所有数据框附加在一起,但发现这很困难.以下是我我正在尝试,请建议如何修复它:
I have a for loop
which produces a data frame after each iteration. I want to append all data frames together but finding it difficult. Following is what I
am trying, please suggest how to fix it:
d = NULL
for (i in 1:7) {
# vector output
model <- #some processing
# add vector to a dataframe
df <- data.frame(model)
}
df_total <- rbind(d,df)
推荐答案
不要在循环内进行.制作一个列表,然后在循环之外将它们组合起来.
Don't do it inside the loop. Make a list, then combine them outside the loop.
datalist = list()
for (i in 1:5) {
# ... make some data
dat <- data.frame(x = rnorm(10), y = runif(10))
dat$i <- i # maybe you want to keep track of which iteration produced it?
datalist[[i]] <- dat # add it to your list
}
big_data = do.call(rbind, datalist)
# or big_data <- dplyr::bind_rows(datalist)
# or big_data <- data.table::rbindlist(datalist)
这是一种更像 R 的做事方式.它也可以显着更快,特别是如果您使用 dplyr::bind_rows
或 data.table::rbindlist
进行数据帧的最终组合.
This is a much more R-like way to do things. It can also be substantially faster, especially if you use dplyr::bind_rows
or data.table::rbindlist
for the final combining of data frames.
这篇关于在 for 循环中将数据帧附加在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文