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

在R语言中将含月份列的表格转换为时间顺序格式

R中宽格式转长格式的简便实现

直接用tidyverse包的pivot_longer函数就能搞定,比merge操作简洁太多,步骤如下:

  • 首先加载依赖包:
library(tidyverse)
  • 假设你的宽格式数据框名为wide_data,行是年份,列是月份(Jan、Feb这类缩写),先把行名转为单独的年份列:
wide_data <- wide_data %>%
  rownames_to_column(var = "Year")
  • 转成包含Date和Value的长格式:
long_data <- wide_data %>%
  # 把除了Year之外的列都转成行,月份存到Month列,对应数值存到Value列
  pivot_longer(cols = -Year, names_to = "Month", values_to = "Value") %>%
  # 拼接月份和年份生成Date列
  mutate(Date = paste(Month, Year))

如果需要数字格式的日期(比如1659-01),可以配合lubridate包转换:

library(lubridate)
long_data <- long_data %>%
  mutate(Date = my(Date)) # 自动转成日期类型,默认日为1

这个方法一步完成宽转长,不需要繁琐的merge操作,灵活适配你需要的日期格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:10:23