我有这个 df:
structure(list(CN = c("BR", "BR", "BR", "PL", "PL", "PL",
"BR", "BR", "BR", "BR", "PL", "PL", "PL"), Year = c(2019,
2019, 2019, 2019, 2019, 2019, 2020, 2020, 2020, 2020, 2020, 2020,
2020), Squad = c("A", "B", "C", "A", "B", "C", "C", "F", "G",
"I", "D", "E", "F"), X = c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3,
1), Y = c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1)), row.names = c(NA,
-13L), class = c("tbl_df", "tbl", "data.frame"))
我想总结(x+y 和小队人数的总和),按 CN 和年份分组;并在同一结构中添加一列,其中包含仅按 CN 分组的小队的唯一/不同值的计数。
它看起来像这样:
structure(list(CN = c("BR", "BR", "PL", "PL"), Year = c(2019,
2020, 2019, 2020), Sum = c(12, 14, 12, 12), n_squad = c(3, 4,
3, 3), n_squad_distinct = c(6, 6, 6, 6)), row.names = c(NA, -4L
), class = c("tbl_df", "tbl", "data.frame"))
谢谢
最佳答案
我们可以通过在“Squad”上应用n_distinct
来创建按“CN”分组的“n_squad_distinct”列,然后将“Year”和“n_squad_distinct”也添加为分组变量并执行总结
library(dplyr)
df %>%
group_by(CN) %>%
mutate(n_squad_distinct = n_distinct(Squad)) %>%
group_by(n_squad_distinct, Year, .add = TRUE) %>%
summarise(Sum = sum(X + Y), n_squad = n_distinct(Squad), .groups = 'drop')
-输出
# A tibble: 4 × 5
CN n_squad_distinct Year Sum n_squad
<chr> <int> <dbl> <dbl> <int>
1 BR 6 2019 12 3
2 BR 6 2020 14 4
3 PL 6 2019 12 3
4 PL 6 2020 12 3
关于r - 使用 dplyr 汇总并统计分组 df 中唯一值的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72791590/