R 总结多个函数
我有一个数据框架,在该数据框架下按县进行分组,然后尝试使用跨越跨的数据来汇总其余数据。 Some of the variables I would like to sum across, while other variables I would like to average across
Here is my sample data:
dat <- data.frame("county" = c("a", "a", "b", "b", "c", "c"),
"pop" = c(10,20,30,40, 40, 20),
"men" = c(5, 15, 15, 25, 15, 10),
"crime_rate"= c(4,3, 2, 1, 6, 2),
"rate_2" = c(1, 2, 1, 4, 3, 10))
here is what I've tried
dat_summary <- dat %>%
group_by(county) %>%
summarise(across(c(pop, men), sum)) %>%
summarise(across(c(crime_rate, rate_2), average))
I know that summarise(across) works if I were to just sum the population or男人的人数,如果我只是尝试找到平均费率的平均值,也将有效 - 但是我如何才能使我既可以工作并为我提供所需信息的摘要数据框架?
我能想到的唯一方法是为总和变量创建一个数据框架分组并汇总,然后重复平均变量,然后将所有变量重复在一起。
我有没有办法在一个代码序列中完成这一切?谢谢! *注意:我与之合作的价格是N/100,000,因此在这种情况下,平均值将工作。
I have a data frame where I am grouping by county, and then trying to summarize teh rest of the data using summarise across. Some of the variables I would like to sum across, while other variables I would like to average across
Here is my sample data:
dat <- data.frame("county" = c("a", "a", "b", "b", "c", "c"),
"pop" = c(10,20,30,40, 40, 20),
"men" = c(5, 15, 15, 25, 15, 10),
"crime_rate"= c(4,3, 2, 1, 6, 2),
"rate_2" = c(1, 2, 1, 4, 3, 10))
here is what I've tried
dat_summary <- dat %>%
group_by(county) %>%
summarise(across(c(pop, men), sum)) %>%
summarise(across(c(crime_rate, rate_2), average))
I know that summarise(across) works if I were to just sum the population or the number of men, and would also work if I just try to find the average of the rates - but how can I get both to work and give me a summary data frame with all the information I need?
The only other way I can think of doing this is to create a data frame grouping and summarizing across for the sum variables, then repeating for the average variables, and then joining all together.
Is there a way for me to do this all in one code sequence? Thanks!
*Note: the rates I am working with are n/100,000, so an average will work in this instance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要按组变量保持恒定,我们就可以在()函数中包含多个
函数
summarize()
使用不同的函数来总结变量的子集输入数据框。...和输出:
As long as the by group variables remain constant we can include multiple
across()
functions within a single invocation ofsummarise()
to use different functions to summarize subsets of variables in the input data frame....and the output: