【问题标题】:Number of categories not equal to a specific one类别数量不等于特定类别
【发布时间】:2018-10-30 21:31:26
【问题描述】:

我有一个包含许多分类列的数据框。 我想计算不等于“bla”的不同类别的数量。 比如:

> d1
# A tibble: 5 x 2
    x      y    
  <chr>  <chr>
1 yellow A    
2 green  A    
3 green  bla  
4 blue   B    
5 bla    bla  

如何修改 dplyr 的

d1 %>% summarise_all(n_distinct)

排除类别“bla”?在这种情况下,x 列的答案应该是 3,y 列的答案应该是 2。

【问题讨论】:

    标签: r dplyr summarize


    【解决方案1】:

    我们可以使用filter_allfilter 所有列中的行,然后使用n_distinct 来获取唯一值的长度。

    library(dplyr)
    
    d1 %>% 
       filter_all(all_vars(. != "bla")) %>% 
        summarise_all(n_distinct)
    
    #  x y
    #1 3 2
    

    【讨论】:

      【解决方案2】:

      使用数据表

      library(data.table)
      
      d1 <- data.table(d1)
      
      d1[!y %like% 'bla', .(count = .N, distinct = uniqueN(x)), by = .(y)]
      

      【讨论】:

        【解决方案3】:

        使用 base::lengths():

        lengths(lapply(d1, function(i) unique(i[ i != "bla" ])))
        # x y 
        # 3 2 
        

        【讨论】:

          猜你喜欢
          • 2015-10-07
          • 1970-01-01
          • 2015-07-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-05
          • 1970-01-01
          相关资源
          最近更新 更多