【问题标题】:count distinct levels of a data frame for groups based on a condition根据条件计算组的数据框的不同级别
【发布时间】:2020-01-29 18:30:26
【问题描述】:

我有以下 DF

x = data.frame('grp' = c(1,1,1,2,2,2),'a' = c(1,2,1,1,2,1), 'b'= c(6,5,6,6,2,6), 'c' = c(0.1,0.2,0.4,-1, 0.9,0.7))

  grp a b    c
1   1 1 6  0.1
2   1 2 5  0.2
3   1 1 6  0.4
4   2 1 6 -1.0
5   2 2 2  0.9
6   2 1 6  0.7 

我想为c >= 0.1 所在的每个组计算不同级别的(a,b)

我已经尝试使用dplyr 使用group_bysummarise,但没有得到想要的结果

x %>% group_by(grp) %>% summarise(count = n_distinct(c(a,b)[c >= 0.1]))

对于上述情况,我希望得到以下结果

    grp count
  <dbl> <int>
1     1     2
2     2     2

但是使用上述查询我得到以下结果

    grp count
  <dbl> <int>
1     1     4
2     2     3

从逻辑上讲,上述输出似乎解决了(a,b) 的 concat 列表的所有唯一值,但不是我需要的 任何指针,非常感谢任何帮助

【问题讨论】:

    标签: r group-by dplyr conditional-statements summarize


    【解决方案1】:

    这是使用dplyr 的另一种方式。听起来您想基于cfilter,所以我们这样做了。在n_distinct中不用c(a, b),我们可以写成n_distinct(a, b)

    x %>%
        filter(c >= 0.1) %>%
        group_by(grp) %>%
        summarise(cnt_d = n_distinct(a, b))
    
    #     grp cnt_d
    #   <dbl> <int>
    # 1     1     2
    # 2     2     2
    

    【讨论】:

      【解决方案2】:

      我们可以 paste ab 列并计算每个组中的不同值。

      library(dplyr)
      
      x %>% 
        mutate(col = paste(a, b, sep = "_")) %>%
        group_by(grp) %>%
        summarise(count = n_distinct(col[c >= 0.1]))
      
      #    grp count
      #  <dbl> <int>
      #1     1     2
      #2     2     2
      

      【讨论】:

      • 谢谢喜欢这个更好,因为它也允许在多种条件下工作
      【解决方案3】:

      使用data.table的选项

      library(data.table)
      setDT(x)[c >= 0.1, .(cnt_d = uniqueN(paste(a, b))), .(grp)]
      #    grp cnt_d
      #1:   1     2
      #2:   2     2
      

      【讨论】:

        猜你喜欢
        • 2022-09-22
        • 1970-01-01
        • 1970-01-01
        • 2021-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多