有效地按列汇总

时间:2018-09-11 19:53:50

标签: r dataframe data.table summarize

我有一个类似于datadf的大表,有3000万列和行,我看到了一些方法可以在堆栈溢出(Frequency of values per column in table)中获得期望的摘要,但是即使最快,对于我的桌子。编辑:谢谢评论,目前有几种方法令人满意。

library(data.table)
library(tidyverse)
library(microbenchmark)

datadf <- data.frame(var1 = rep(letters[1:3], each = 4), var2 = rep(letters[1:4], each = 3), var3 = rep('m', 12), stringsAsFactors = F )
datadf <- datadf[sample(1:nrow(datadf), 1000, T),sample(1:ncol(datadf), 1000, T)]
dataDT <- as.data.table(datadf)
lev<-unique(unlist(datadf))

microbenchmark(
 #base EDITED based on comment
 sapply(datadf, function(x) table(factor(x, levels=lev, ordered=TRUE))), #modified based on comment

 #tidyverse EDITED based on comment
 datadf %>% gather() %>% count(key, value) %>% spread(key, n, fill = 0L), # based on comment

 #data.table
  dcast(melt(dataDT, id=1:1000, measure=1:1000)[,1001:1002][, `:=` (Count = .N), by=.(variable,value)], value ~ variable ,
        value.var = "value", fun.aggregate = length),

 # EDITED, In Answer below
 dcast.data.table(
    melt.data.table(dataDT, measure.vars = colnames(dataDT))[, .N, .(variable, value)],
    value ~ variable,
    value.var = "N",
    fill = 0
  ),
  times=1
)

       min          lq        mean      median          uq         max  neva
   86.8522     86.8522     86.8522     86.8522     86.8522     86.8522     1
  207.6750    207.6750    207.6750    207.6750    207.6750    207.6750     1
12207.5694  12207.5694  12207.5694  12207.5694  12207.5694  12207.5694     1 
   46.3014     46.3014     46.3014     46.3014     46.3014     46.3014     1 # Answer      

0 个答案:

没有答案