在R中迭代构造的数据帧 [英] iteratively constructed dataframe in R
本文介绍了在R中迭代构造的数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 创建空数据框,每次迭代添加一行
- 预分配nxl数据帧,修改行每次迭代
- 预分配nxl矩阵,每次迭代修改一行,使矩阵中的数据框
- 其他
- Create empty dataframe, add a row each iteration
- Preallocate n x l dataframe, modify a row each iteration
- Preallocate n x l matrix, modify a row each iteration, make dataframe from matrix
- Something else
解决方案
预先分配!!!
并使用 matrix
如果数据是相同的类型。这将比一个 data.frame
快得多。
例如:
> n < - 1000#行数
>行< - 1:20 * 1#一行
>
> #添加行,一个一个
>数据< - data.frame()
> system.time(for(i in 1:n)数据< - rbind(数据,行))
用户系统已用
2.18 0.00 2.18
>
> #预先分配的data.frame
>数据< - as.data.frame(Data)
> system.time(for(i in 1:n)Data [i,]< - row)
用户系统已用
0.94 0.00 0.93
>
> #预分配矩阵(fast!)
>数据< - as.matrix(Data)
> system.time({for(i in 1:n)Data [i,]< - row; Data< - as.data.frame(Data)})
用户系统已用
0 0 0
I'm relatively new to R, and was wondering the most efficient way to iteratively construct a dataframe (one row at a time, the number of iterations "n" and the length of each row "l" are known beforehand).
解决方案
Pre-allocate!!!
And use a matrix
if the data are all the same type. It will be much faster than a data.frame
.
For example:
> n <- 1000 # Number of rows
> row <- 1:20*1 # one row
>
> # Adding row, one-by-one
> Data <- data.frame()
> system.time(for(i in 1:n) Data <- rbind(Data,row))
user system elapsed
2.18 0.00 2.18
>
> # Pre-allocated data.frame
> Data <- as.data.frame(Data)
> system.time(for(i in 1:n) Data[i,] <- row)
user system elapsed
0.94 0.00 0.93
>
> # Pre-allocated matrix (fast!)
> Data <- as.matrix(Data)
> system.time({ for(i in 1:n) Data[i,] <- row; Data <- as.data.frame(Data) })
user system elapsed
0 0 0
这篇关于在R中迭代构造的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文