【问题标题】:Increase speed with rbindlist does not work with two for loops使用 rbindlist 提高速度不适用于两个 for 循环
【发布时间】:2015-04-03 13:59:33
【问题描述】:

我有一个看起来像这样的数据集:

test <- data.table(Weight=sample(x = c(20:100),500,replace = T),y=rnorm(500),z=rnorm(500))

> head(test)
   Weight          y           z
1:     87 -0.7946846 -0.03136408
2:     97  1.6570765  0.61080309
3:     80  1.1592073 -0.09389739
4:     23 -0.0268602 -1.36896141
5:     32  1.3171078 -2.19978789
6:     78 -0.1961162  0.62026338

我想复制每一行的次数与权重下的值一样多。我通过以下代码实现了这一点:(我包含了一个进度条)

system.time(
  for (i in 1:nrow(test)){
    setTxtProgressBar(pb,i)
    for (j in 1:test[i,]$Weight){
      Testoutcome <- rbind(Testoutcome, test[i,])
    }
  })
user  system elapsed 
  32.91    0.08   33.57 

我发现一个帖子here 解释说 rbindlist 比 rbind 快得多。所以我修改了这样的代码:

system.time(
  for (i in 1:nrow(test)){
    setTxtProgressBar(pb,i)
    for (j in 1:test[i,]$Weight){
      Testoutcome <- rbindlist(list(Testoutcome, test[i,]))
    }
  })
user  system elapsed 
  27.72    0.05   28.31

所以它似乎没有那么有效。我的实际数据集大约大 1.000 倍,而且查询需要很长时间......有什么想法可以加快速度吗?也许我应该在循环外绑定?

【问题讨论】:

标签: r for-loop data.table rbind


【解决方案1】:

这应该很快,而且很简单:

test[rep(1:.N,Weight)]

【讨论】:

  • 谢谢,我过于关注 rbind 和 rbindlist。
猜你喜欢
  • 1970-01-01
  • 2019-08-01
  • 2020-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-17
  • 2020-10-21
相关资源
最近更新 更多