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

如何从多个长数据库中选取单个变量生成宽数据库?

提取多年份数据中Transport变量并汇总为宽表

需求说明

从多个单年份的长格式数据库中,提取每个Name对应的Type=Transport的Value,最终汇总成以Name为行、年份为列的宽表。

解决步骤(基于R的tidyverse工具包)

  1. 合并所有年份的数据:将各年份的数据库合并为一个完整数据集
  2. 筛选目标记录:仅保留Type为Transport的行
  3. 转换为宽表:将年份转为列名,对应填充Transport的数值

代码实现

# 加载所需包
library(tidyverse)

# 模拟示例数据(实际使用时替换为读取你的数据库)
df_2020 <- tibble(
  Name = rep(c("A", "B", "C"), each = 3),
  Year = 2020,
  Type = rep(c("Transport", "Building", "Park"), 3),
  Value = c(24531, 3545, 65, 9454, 15654, 75, 2342, 4681, 45)
)

df_2021 <- tibble(
  Name = rep(c("A", "B", "C"), each = 3),
  Year = 2021,
  Type = rep(c("Transport", "Building", "Park"), 3),
  Value = c(34531, 13513, 65, 13454, 17655, 75, 2345, 6357, 56)
)

# 1. 合并所有年份数据
combined_df <- bind_rows(df_2020, df_2021)

# 2. 筛选Transport类型的记录
transport_df <- combined_df %>%
  filter(Type == "Transport")

# 3. 转换为宽表
final_df <- transport_df %>%
  pivot_wider(
    id_cols = Name,          # 以Name作为行标识
    names_from = Year,       # 将Year列的内容作为新列名
    values_from = Value      # 将Value列的内容填充到对应年份列
  )

# 查看结果
print(final_df)

输出结果

Name20202021
A2453134531
B945413454
C23422345

常见问题说明

如果之前使用pivot_wide失败,大概率是以下原因:

  • 未提前合并各年份数据,单年份数据无法生成多列的宽表
  • 未筛选Type=Transport,导致同一Name和Year下有多条不同Type的记录,无法正确转换
  • id_cols或names_from参数设置错误,未指定正确的行标识和列名来源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 13:50:45