代码之家  ›  专栏  ›  技术社区  ›  Omry Atia

不等于特定类别的类别数

  •  2
  • Omry Atia  · 技术社区  · 7 年前

    我有一个带有许多分类列的数据框架。 我想计算不等于“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  
    

    如何修改dpylr的

    d1 %>% summarise_all(n_distinct)
    

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

    3 回复  |  直到 7 年前
        1
  •  1
  •   zx8754    7 年前

    使用 基::长度() :

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

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

    library(dplyr)
    
    d1 %>% 
       filter_all(all_vars(. != "bla")) %>% 
        summarise_all(n_distinct)
    
    #  x y
    #1 3 2
    
        3
  •  0
  •   fidelin    7 年前

    使用数据表

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