宽表转长表:含嵌套结构的数据框重塑问题
宽格式数据框转长格式(处理嵌套维度)
需求说明
现有宽格式数据框,其中nearbypanels类列包含年份和住宅半径两个嵌套维度,heatpump类列仅包含年份维度。需要将数据转换为目标格式,最终得到dwelling(原住宅ID+年份)、heatpump、nearbypanels_250m、nearbypanels_500m四列。
原数据框定义:
df <- data.frame(dwelling=c('A', 'B', 'C', 'D'), nearbypanels2020_250m=c(12, 15, 19, 19), nearbypanels2019_250m=c(22, 29, 18, 12), nearbypanels2020_500m=c(23, 16, 22, 33), nearbypanels2019_500m=c(24, 31, 19, 14), heatpump2020=c(20,25,21,19), heatpump2019=c(19,24,18,12))
解决方案(使用tidyverse工具)
通过格式转换、字符串拆分、重新整理三步完成,代码如下:
library(tidyverse) result <- df %>% # 将所有指标列转成长格式,暂存列名和对应值 pivot_longer(cols = -dwelling, names_to = "variable", values_to = "value") %>% # 从列名中提取年份,分离指标和半径维度 mutate(year = str_extract(variable, "\\d{4}"), indicator_radius = str_remove(variable, "\\d{4}")) %>% separate(indicator_radius, into = c("indicator", "radius"), sep = "_", fill = "right") %>% # 重新转成宽格式,按指标+半径命名列 pivot_wider(names_from = c(indicator, radius), values_from = value, names_sep = "_") %>% # 合并住宅ID和年份,调整列名与顺序 mutate(dwelling = paste0(dwelling, year)) %>% select(dwelling, heatpump_, nearbypanels_250m, nearbypanels_500m) %>% rename(heatpump = heatpump_) # 查看结果 print(result)
输出结果
运行后得到的结果与期望一致:
| dwelling | heatpump | nearbypanels_250m | nearbypanels_500m |
|---|---|---|---|
| A2019 | 19 | 22 | 24 |
| A2020 | 20 | 12 | 23 |
| B2019 | 24 | 29 | 31 |
| B2020 | 25 | 15 | 16 |
| C2019 | 18 | 18 | 19 |
| C2020 | 21 | 19 | 22 |
| D2019 | 12 | 12 | 14 |
| D2020 | 19 | 19 | 33 |
内容的提问来源于stack exchange,提问作者TvCasteren
相关产品推荐
相关产品推荐

