目的是为数据框中的因子/字符串变量创建指标。该数据帧具有> 2mm的行,并且在Windows上运行R,我没有选择将plyr与.parallel = T一起使用。因此,我采用plyr和reshape2进行“分而治之”的路线。

运行熔解和强制转换会耗尽内存,并使用

ddply( idata.frame(items) , c("ID") , function(x){
       (    colSums( model.matrix( ~ x$element - 1) ) > 0   )
} , .progress="text" )

或者
ddply( idata.frame(items) , c("ID") , function(x){
           (    elements %in% x$element   )
    } , .progress="text" )

确实需要一段时间。最快的方法是在下面轻按。您看到加快速度的方法了吗? %in%语句的运行速度比model.matrix调用快。谢谢。
set.seed(123)

dd <- data.frame(
  id  = sample( 1:5, size=10 , replace=T ) ,
  prd = letters[sample( 1:5, size=10 , replace=T )]
  )

prds <- unique(dd$prd)

tapply( dd$prd , dd$id , function(x) prds %in% x )

最佳答案

对于此问题,软件包bigmemorybigtabulate可能是您的 friend 。这是一个更具雄心的示例:

library(bigmemory)
library(bigtabulate)

set.seed(123)

dd <- data.frame(
  id = sample( 1:15, size=2e6 , replace=T ),
  prd = letters[sample( 1:15, size=2e6 , replace=T )]
  )

prds <- unique(dd$prd)

benchmark(
bigtable(dd,c(1,2))>0,
table(dd[,1],dd[,2])>0,
xtabs(~id+prd,data=dd)>0,
tapply( dd$prd , dd$id , function(x) prds %in% x )
)

基准测试的结果(我一直在学习新事物):
                                            test replications elapsed relative user.self sys.self user.child sys.child
1                      bigtable(dd, c(1, 2)) > 0          100  54.401 1.000000    51.759    3.817          0         0
2                    table(dd[, 1], dd[, 2]) > 0          100 112.361 2.065422   107.526    6.614          0         0
4 tapply(dd$prd, dd$id, function(x) prds %in% x)          100 178.308 3.277660   166.544   13.275          0         0
3                xtabs(~id + prd, data = dd) > 0          100 229.435 4.217478   217.014   16.660          0         0

这表明bigtable赢了很多。结果几乎是所有prd都包含在所有ID中,但有关结果格式的详细信息,请参见?bigtable

关于r - 在大型数据框中生成指标,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9878356/

10-10 20:36
查看更多