在R中迭代构造的数据帧 [英] iteratively constructed dataframe in R

查看:98
本文介绍了在R中迭代构造的数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对R来说比较新,并且想知道迭代构造数据帧的最有效的方式(一次一行,迭代次数n,每行l的长度都是事先知道的)


  1. 创建空数据框,每次迭代添加一行

  2. 预分配nxl数据帧,修改行每次迭代

  3. 预分配nxl矩阵,每次迭代修改一行,使矩阵中的数据框

  4. 其他


    1. 解决方案

      预先分配!!!



      并使用 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).

      1. Create empty dataframe, add a row each iteration
      2. Preallocate n x l dataframe, modify a row each iteration
      3. Preallocate n x l matrix, modify a row each iteration, make dataframe from matrix
      4. Something else

      解决方案

      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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆