求助:在R中实现区域/行业/所有权维度的数据透视转置
R语言数据透视解决方案:将季度分月数据转为年月宽格式
步骤说明
你的需求是把包含季度分月(mnth1emp/mnth2emp/mnth3emp)的数据,转换为每个naicscode/areavalue/ownership组合一行、列对应每个年月(如202001)的宽格式。可以通过数据重塑+透视两步完成,使用dplyr和tidyr包实现:
代码实现
首先加载依赖包:
library(dplyr) library(tidyr)
- 将季度分月列转为长格式,提取季度内月份偏移
test_long <- test %>% pivot_longer(cols = starts_with("mnth"), names_to = "month_in_quarter", values_to = "emp") %>% mutate(month_offset = as.integer(substr(month_in_quarter, 4, 4)) - 1)
- 计算每个记录对应的具体年月
test_long <- test_long %>% mutate( # 把季度转为对应起始月份 quarter_start_month = case_when( period == "01" ~ 1, period == "02" ~ 4, period == "03" ~ 7, period == "04" ~ 10 ), # 计算具体月份 month = quarter_start_month + month_offset, # 生成YYYYMM格式的年月字符串 year_month = paste0(periodyear, sprintf("%02d", month)) ) %>% select(naicscode, areavalue, ownership, year_month, emp)
- 透视为目标宽格式
test_wide <- test_long %>% pivot_wider( names_from = year_month, values_from = emp, fill_value = NA # 缺失值填充,可根据需求改为0或其他 )
结果验证
查看test_wide,会得到你期望的格式:每个区域/行业/所有权组合一行,列是从202001到202112的年月,对应数值为各月的emp数据。比如areavalue="000000"的行,202001对应25000,202002对应25005,和你给出的示例一致。
这个方法适用于大规模数据集,多行业、多年份的场景都能兼容。
内容的提问来源于stack exchange,提问作者Tim Wilcox
相关产品推荐
相关产品推荐

