数据组中的组功能缓慢.表r



我的实验设计在各种森林中都测量了树,多年来重复测量。

DT <- data.table(forest=rep(c("a","b"),each=6),
                    year=rep(c("2000","2010"),each=3),
                    id=c("1","2","3"),
                    size=(1:12))
DT[,id:=paste0(forest,id)]
> DT
    forest year id size
 1:     a 2000 a1     1
 2:     a 2000 a2     2
 3:     a 2000 a3     3
 4:     a 2010 a1     4
 5:     a 2010 a2     5
 6:     a 2010 a3     6
 7:     b 2000 b1     7
 8:     b 2000 b2     8
 9:     b 2000 b3     9
10:     b 2010 b1    10
11:     b 2010 b2    11
12:     b 2010 b3    12

对于每棵树i,我想计算一个新变量,等于同一组/年中所有其他个体的大小的避免,这些变量大于树i。

我创建了以下功能:

f.new <- function(i,n){ 
 DT[forest==DT[id==i, unique(forest)] & year==n # select the same forest & year of the tree i
 & size>DT[id==i & year==n, size], # select the trees larger than the tree i
 sum(size, na.rm=T)] # sum the sizes of all such selected trees
}

在数据表中应用时,我得到了正确的结果。

       DT[,new:=f.new(id,year), by=.(id,year)]
> DT
    forest year id size new
 1:     a 2000 a1     1   5
 2:     a 2000 a2     2   3
 3:     a 2000 a3     3   0
 4:     a 2010 a1     4  11
 5:     a 2010 a2     5   6
 6:     a 2010 a3     6   0
 7:     b 2000 b1     7  17
 8:     b 2000 b2     8   9
 9:     b 2000 b3     9   0
10:     b 2010 b1    10  23
11:     b 2010 b2    11  12
12:     b 2010 b3    12   0

请注意,我有一个大型数据集,上面有几个森林(40)&amp;重复年(6)&amp;单个人(20,000),总计近50,000次测量。当我执行上述功能时,需要8-10分钟(Windows 7,i5-6300U CPU @ 2.40 GHz 2.40 GHz,RAM 8 GB)。我需要经常通过几个小修改重复,这需要很多时间。

  1. 有什么更快的方法吗?我检查了 *应用功能,但无法根据它们找到解决方案。
  2. 我可以制作一个不依赖数据集的特定结构的通用函数(即我可以用作"大小"不同的列)?

只要对数据进行排序,这可能非常快:

setorder(DT, forest, year, -size)
DT[, new := cumsum(size) - size, by = .(forest, year)]
setorder(DT, forest, year, id)
DT
#    forest year id size new
# 1:      a 2000 a1    1   5
# 2:      a 2000 a2    2   3
# 3:      a 2000 a3    3   0
# 4:      a 2010 a1    4  11
# 5:      a 2010 a2    5   6
# 6:      a 2010 a3    6   0
# 7:      b 2000 b1    7  17
# 8:      b 2000 b2    8   9
# 9:      b 2000 b3    9   0
#10:      b 2010 b1   10  23
#11:      b 2010 b2   11  12
#12:      b 2010 b3   12   0

最新更新