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

在R中将数据集的日期从列转换为行的实现方法

在R中将宽格式失业数据转换为长格式

原始宽格式数据

先构造出你提供的宽格式数据框:

unemp_wide <- data.frame(
  Country = c("Belgium", "Bulgaria"),
  `2021-08` = c(332, 162),
  `2021-09` = c(323, 157),
  `2021-10` = c(312, 152)
)

方法一:使用tidyverse工具(推荐)

tidyverse中的tidyr::pivot_longer是处理宽转长最直观的函数,步骤如下:

library(tidyverse)

unemp_long <- unemp_wide %>%
  pivot_longer(
    cols = -Country,  # 排除不需要转换的Country列
    names_to = "Date",  # 将原日期列名存入新列Date
    values_to = "Unemployment"  # 将原单元格的失业数据存入新列Unemployment
  )

# 查看转换结果
print(unemp_long)

运行后会得到目标长格式数据,输出如下:

# A tibble: 6 × 3
  Country   Date    Unemployment
  <chr>     <chr>          <dbl>
1 Belgium   2021-08          332
2 Belgium   2021-09          323
3 Belgium   2021-10          312
4 Bulgaria  2021-08          162
5 Bulgaria  2021-09          157
6 Bulgaria  2021-10          152

方法二:使用基础R的reshape函数

如果不想加载额外包,也可以用基础R自带的reshape函数:

unemp_long_base <- reshape(
  unemp_wide,
  direction = "long",  # 指定转换方向为长格式
  varying = colnames(unemp_wide)[-1],  # 指定要转换的日期列
  v.names = "Unemployment",  # 失业数据列的名称
  timevar = "Date",  # 日期列的名称
  times = colnames(unemp_wide)[-1],  # 日期值的来源
  idvar = "Country"  # 标识行的列(不参与转换)
)

# 调整行顺序并重置行名
unemp_long_base <- unemp_long_base[order(unemp_long_base$Date), ]
rownames(unemp_long_base) <- NULL

print(unemp_long_base)

输出结果与tidyverse方法一致:

Country    Date Unemployment
1   Belgium 2021-08          332
2  Bulgaria 2021-08          162
3   Belgium 2021-09          323
4  Bulgaria 2021-09          157
5   Belgium 2021-10          312
6  Bulgaria 2021-10          152

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:35:14