R语言dplyr分组统计中summarise()函数报错:'has grouped output by 'year'. You can override using the '.groups' argument.' 解决方案

在使用R语言的dplyr包进行数据处理时,我们经常使用group_by()summarise()函数进行分组统计。然而,有时在使用summarise()函数时会遇到如下报错信息:

'has grouped output by 'year'. You can override using the '.groups' argument.'

报错原因:

这个报错信息表明summarise()函数默认会保留分组变量(本例中是'year'),导致输出结果仍然按照'year'分组。

解决方案:

要解决这个问题,我们可以在summarise()函数中添加.groups参数,并将其设置为'drop',从而取消分组。

示例代码:

假设我们有一个名为bnames的数据集,其中包含'year'(年份)、'name'(名字)、'percent'(出现百分比)和'sex'(性别)等列。我们想要按照年份、名字和性别分组,并计算每个组的总出现百分比。以下代码演示了如何使用.groups = 'drop'解决报错问题:Rlibrary(dplyr)library(ggplot2)

假设bnames数据集中有year表示年份,name表示名字,percent表示出现百分比,sex表示性别

按照年份、名字和性别分组,并计算每个组的总出现百分比name_counts <- bnames %>% group_by(year, name, sex) %>% summarise(total_percent = sum(percent), .groups = 'drop')

找到每个名字在每年的最高出现百分比most_popular_years <- name_counts %>% group_by(name, sex) %>% filter(total_percent == max(total_percent)) %>% select(name, sex, year)

绘制名字的变化趋势图ggplot(most_popular_years, aes(x = year, y = total_percent, color = sex)) + geom_line() + facet_wrap(~ name, scales = 'free_y') + labs(title = '变化趋势图', x = '年份', y = '出现百分比')

代码解释:

  • summarise()函数中,我们添加了.groups = 'drop'参数,这将取消分组,并返回一个非分组的数据框。* 其余代码保持不变,用于找到每个名字在每年的最高出现百分比,并绘制变化趋势图。

总结:

当遇到summarise()函数报错'has grouped output by...'时,我们只需要在函数中添加.groups = 'drop'参数即可解决问题。

R语言dplyr分组统计中summarise()函数报错:has grouped output by 'year'. You can override using the '.groups' argument.解决方案

原文地址: https://www.cveoy.top/t/topic/ocy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录