如何用mutate()和case_when()创建年代变量并绘制GDP总和柱状图?
解决方案
1. 创建decade变量
先加载dplyr包以支持case_when()和管道操作,再在筛选后的数据集g中添加目标变量:
library(dplyr) # 通过case_when()生成decade变量 g <- g %>% mutate( decade = case_when( year >= 1950 & year < 1960 ~ "1950s", year >= 1960 & year < 1970 ~ "1960s", year >= 1970 & year < 1980 ~ "1970s", year >= 1980 & year < 1990 ~ "1980s", year >= 1990 & year < 2000 ~ "1990s", year >= 2000 & year < 2010 ~ "2000s", year >= 2010 ~ "2010s", TRUE ~ "Unknown" # 兼容超出上述范围的年份 ) )
可选简化写法
如果不想手动枚举年份区间,可通过年份计算自动生成decade,代码更简洁且易维护:
g <- g %>% mutate(decade = paste0(floor(year / 10) * 10, "s"))
2. 计算GDP总和并绘制柱状图
原数据集无直接总GDP字段,需先通过人均GDP×人口计算,再按区域和十年分组求和,最后用ggplot2生成可视化图表:
library(ggplot2) # 按区域、十年分组计算GDP总和 gdp_summary <- g %>% mutate(total_gdp = gdp_per_capita * population) %>% group_by(region, decade) %>% summarise(total_gdp_sum = sum(total_gdp, na.rm = TRUE)) %>% ungroup() # 绘制并列柱状图 ggplot(gdp_summary, aes(x = decade, y = total_gdp_sum, fill = region)) + geom_col(position = position_dodge(width = 0.8)) + scale_y_continuous(labels = scales::dollar_format(scale = 1e-12, suffix = "T")) + # 格式化y轴为万亿美元 labs( title = "各区域国家每十年GDP总和", x = "十年区间", y = "GDP总和(万亿美元)", fill = "区域" ) + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) # 旋转x轴标签避免重叠
代码说明
total_gdp = gdp_per_capita * population:推导总GDP字段,适配原数据集结构。position = position_dodge():生成并列柱状图,便于跨区域对比;若需堆叠展示,移除该参数即可。scales::dollar_format():优化大数值可读性,将GDP转换为万亿美元单位。
内容的提问来源于stack exchange,提问作者AB3
相关产品推荐
相关产品推荐

