总结并计算DPLYR分组DF中唯一值的数量
我有这个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"))
我想总结CN和年分组的(X+Y和小队计数的总和);在相同的结构中,添加了一个仅由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"))
谢谢
I have this 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"))
I want to summarize (sum of x+y and squad count) grouped by CN and Year; and in the same structure add a column with the count of unique/distinct values for squad grouped by CN only.
It would look like this:
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"))
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我们可以通过在'squead'上应用
n_distinct
来创建由'cn'分组的'n_squad_distinct'列,然后添加'Year''和'N_squad_distinct',也将“ n_squad_distinct”分组为分组变量- 输出
We may create the 'n_squad_distinct' column grouped by 'CN" by applying
n_distinct
on the 'Squad', then add the 'Year' and 'n_squad_distinct' also as grouping variables and do thesummarise
-output