从空数据框开始,我需要按如下方式填充数据框:for循环在每次迭代中生成固定数量的值,我需要添加一个包含该列表中值的新列,并为该列指定唯一名称,col_i(其中i是循环的第i次迭代).
怎么能(看似简单的任务)完成?
分段构建数据框架的最有效方法是将您的零件存储在预先分配的列表中,然后将它们放在一起.
例如:
num.iters <- 10
l <- vector('list', num.iters)
for (i in 1:num.iters) {
l[[i]] <- rnorm(3) # the column data
names(l)[i] <- paste('Col', i, sep='.') # the column name
}
do.call(cbind, l) # ... if your cols are the same datatype and you want a matrix
data.frame(l) # otherwise
Run Code Online (Sandbox Code Playgroud)