代码之家  ›  专栏  ›  技术社区  ›  frank

每列中特定值的次数R

  •  1
  • frank  · 技术社区  · 4 年前

    我有:

    library(tidyverse)
    df <- tibble(one=c(1,1,1,2,2,2,3,3),
           log1 = c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE),
           log2 = c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE),
           log3 = c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE))
    

    enter image description here

    我想找出单词“FALSE”在每个列和组中出现的次数,并返回一个df

    enter image description here

    我试过了 map_df(df, function(x) sum(x==FALSE))

    df %>%
      group_by(one) %>%
      map_df( function(x) sum(x==FALSE))
    

    但他们不会分成不同的群体。

    这也会出错

    df %>%
      group_by(one) %>%
      summarise( function(x) sum(x==FALSE))
    

    有什么建议吗?

    1 回复  |  直到 4 年前
        1
  •  2
  •   Andre Wildberg    4 年前

    你可以用 across 要处理多个列

    library(dplyr)
    
    df %>% 
      group_by(one) %>% 
      summarise(across(starts_with("log"), function(x) sum(x==F)))
    # A tibble: 3 × 4
        one  log1  log2  log3
      <dbl> <int> <int> <int>
    1     1     1     1     1
    2     2     3     3     3
    3     3     0     2     1
    

    一个简单的方法是直接使用布尔值,正如@RuiBarradas所提到的

    ...
    summarise(across(starts_with("log"), function(x) sum(!x)))
    ...