将列名和组参数作为变量传递给data.table

时间:2018-10-31 11:21:40

标签: r dplyr data.table

我正在尝试计算不同群组的用户数。我找到了一种使用dplyr进行操作的方法,但我想使用data.table实现解决方案,从而提高效率并作为练习。

我在此示例中使用的库:

   library(dplyr)
   library(magrittr)
   library(data.table)

假设我有这个df:

df <- data.frame(V1 = sample(c("a", "b", "c"), 11, TRUE), 
                 V2 = sample(c("2016", "2017", "2018"), 11, TRUE),
                 V3 = sample(seq(1:3), 11, TRUE), 
                 V4 = sample(seq(1:3), 11, TRUE),
                 Id = sample(seq(1:5), 11, TRUE))

使用dplyr的解决方案是:

for (grp in c("V1", "V2", "V3", "V4")) {
    col <- paste0(grp, "_user_cnt")
    df %<>%
    group_by_(grp) %>%
    mutate(!!col := n_distinct(Id)) %>%
    ungroup()
}

我对data.table的处理方式如下:

DT <- data.table(df)
for (grp in c("V1", "V2", "V3", "V4")) {
    col <- paste0(grp, "_user_cnt")
    DT[, (deparse(col)) := n_distinct(Id), by = get(grp)]
}

问题是我找不到正确传递colgrp的方法,这种方法可以正确计算所有内容,但使用引号括起来,这很讨厌并导致错误。我已经尝试过here建议的技术,以及this SO question的答案和评论。但是它们似乎都不起作用。我在做什么错了?

0 个答案:

没有答案
相关问题