使用 tidyverse 对 tibble 中的变量求和

summing the variables in tibble using tidyverse

如何通过将 TRUE 条件视为“1”并将 db 中每个变量的计数相加来转换以下输入。如果为 FALSE,则为零。

输入

db  type1 type2
t1  TRUE FALSE
t1  TRUE FALSE
t1  TRUE FALSE
t2  TRUE FALSE
t3  FALSE TRUE
t3  FALSE TRUE

输出

db  type1 type2
t1  3 0
t2  1 0
t3  0 2

sum R 中的函数将 TRUE 视为 1,将 FALSE 视为 0,因此它很简单:

df %>% group_by(db) %>% summarize_all(sum)

# A tibble: 3 x 3
#      db type1 type2
#  <fctr> <int> <int>
#1     t1     3     0
#2     t2     1     0
#3     t3     0     2

summarize_all 汇总除组变量之外的所有列。