You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

宽表转长表:含嵌套结构的数据框重塑问题

宽格式数据框转长格式(处理嵌套维度)

需求说明

现有宽格式数据框,其中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)

输出结果

运行后得到的结果与期望一致:

dwellingheatpumpnearbypanels_250mnearbypanels_500m
A2019192224
A2020201223
B2019242931
B2020251516
C2019181819
C2020211922
D2019121214
D2020191933

内容的提问来源于stack exchange,提问作者TvCasteren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 01:37:16