R计算每行的出现次数非常慢

时间:2018-05-21 09:46:30

标签: r dataframe dplyr

我试图在每行数据帧中得到一个值的所有出现,如下所示:

     a   b  c  d  e
  1  1   1  0 -1 NA
  2  0  -1 -1  1 NA
  3  -1  0 NA NA  1

到这个

     a   b  c  d  e count.-1 count.0 count.1 count.NA
  1  1   1  0 -1 NA        1       1       2        1
  2  0  -1 -1  1 NA        2       1       1        1
  3  1   0 NA NA  1        0       1       2        2

我现在正在这样做:

    df = df %>%
  by_row(
    ..f = function(x) {
      sum(is.na(x[1:8]))
    },
    .to = "count_na",
    .collate = "cols"
  ) %>% 
  by_row(
    ..f = function(x) {
      sum(x[1:8] == 1, na.rm = T)
    },
    .to = "count_positive",
    .collate = "cols"
  ) %>% 
  by_row(
    ..f = function(x) {
      sum(x[1:8] == -1, na.rm = T)
    },
    .to = "count_negative",
    .collate = "cols"
  ) %>% 
  by_row(
    ..f = function(x) {
      sum(x[1:8] == 0, na.rm = T)
    },
    .to = "count_neutral",
    .collate = "cols"
  ) 

然而问题是,对于5密耳的行,这需要永远完成(超过3小时,是否有更好的方法来做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以使用data.table进行快速处理。首先,融入长格式然后按行数和值列表,然后再回转并加入以获得所需的输出

agg <- dcast(melt(DT[, rn:=.I], id.vars="rn")[, .N, by=.(rn, value)], 
    rn ~ value, sum, value.var="N")
DT[agg, on=.(rn)]

示例数据:

library(data.table)
set.seed(0L)
DT <- as.data.table(matrix(sample(c(-1L, 0L, 1L, NA_integer_), 5*5e6, replace=TRUE), ncol=5))
DT

编辑:添加了一些时间。对于使用data.table

的500万行数据集,tl; dr大约10秒
dtmtd <- function() {
    agg <- dcast(melt(DT[, rn:=.I], id.vars="rn")[, .N, by=.(rn, value)], 
        rn ~ value, sum, value.var="N")
    DT[agg, on=.(rn)]

}    
microbenchmark::microbenchmark(dtmtd(), times=3L)

定时:

Unit: seconds
    expr      min       lq     mean  median       uq      max neval
 dtmtd() 10.07663 10.14351 10.17387 10.2104 10.22249 10.23458     3