繁体   English   中英

group_by 按名称前缀汇总

[英]group_by summarise by name prefix

我的实际数据集比下面的虚拟数据复杂一点。 我想告诉 R 对以前缀“cat_”开头的任何变量进行求和汇总。 现在我正在单独做。 有什么建议么?

dput(df)
structure(list(ID = c("A", "B", "C", "D", "A", "B", "C", "D", 
"A", "B", "C", "D"), year = c(1900, 1900, 1900, 1900, 1901, 1901, 
1901, 1901, 1902, 1902, 1902, 1902), val = c(2635L, 8573L, 5942L, 
7390L, 8762L, 7871L, 7848L, 1928L, 6772L, 6487L, 6005L, 5341L
), cat_TS = c(1L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), 
    cat_1 = c(0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L), 
    cat_2 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L)), row.names = c(NA, 
-12L), class = c("tbl_df", "tbl", "data.frame"))

df <- df %>% group_by(ID) %>% 
  summarise(cat_TS = sum(cat_TS), cat_1 = sum(cat_1), cat_2 = sum(cat_2))

使用dplyr::starts_with到 dplyr:: dplyr::across中以名称'cat'开头的 select 列对summarise中的所有这些列进行求和。

library(dplyr)

df %>% group_by(ID) %>%
  summarise(
    across(starts_with("cat"), sum)
  )

# # A tibble: 4 × 4
#   ID    cat_TS cat_1 cat_2
#   <chr>  <int> <int> <int>
# 1 A          1     1     1
# 2 B          0     1     0
# 3 C          0     0     0
# 4 D          1     0     0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM