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

如何在R语言中为月度数据生成M01格式的周期列

给月度数据新增周期列(M01-M12)的实现方法

问题描述

我有月度数据,需要新增一个Period列,规则为:一月对应M01、二月对应M02……十二月对应M12,请问如何实现?

原始数据

情况1:Month列包含月份与年份

unemployment = data.frame(Month = c("Sept 2002", "Oct 2002", "Nov 2002", "Dec 2002", "Jan 2003", "Feb 2003"), 
                   Total = c(5.7, 5.7, 5.9, 6, 5.8, 5.9))

数据预览:

Month Total
1 Sept 2002   5.7
2  Oct 2002   5.7
3  Nov 2002   5.9
4  Dec 2002   6.0
5  Jan 2003   5.8
6  Feb 2003   5.9

情况2:Month与Year列分离(完整12个月示例)

structure(list(Month = c("Jan", "Feb", "Mar", "Apr", "May", "June"), 
               Year = c("2003", "2003", "2003", "2003", "2003", "2003"), 
               Unemp_percent = c(5.8, 5.9, 5.9, 6, 6.1, 6.3)), 
          row.names = 5:10, class = "data.frame")

期望结果

新增Period列后的目标格式:

Month Period Total
1 Sept 2002   M09   5.7
2  Oct 2002   M10   5.7
3  Nov 2002   M11   5.9
4  Dec 2002   M12   6.0
5  Jan 2003   M01   5.8
6  Feb 2003   M02   5.9

解决方案

方法1:基础R原生实现

利用R内置的月份缩写向量month.abb匹配月份数字,再通过sprintf补前导零生成目标格式。

适配情况1(Month含年月)

# 提取月份缩写(取字符串前3位)
unemployment$month_abbr <- substr(unemployment$Month, 1, 3)
# 匹配对应月份数字
unemployment$month_num <- match(unemployment$month_abbr, month.abb)
# 生成Period列,补前导零确保两位数
unemployment$Period <- sprintf("M%02d", unemployment$month_num)
# 调整列顺序并移除临时列
unemployment <- unemployment[, c("Month", "Period", "Total")]

适配情况2(Month与Year分离)

直接用Month列匹配即可:

df <- structure(list(Month = c("Jan", "Feb", "Mar", "Apr", "May", "June"), 
                     Year = c("2003", "2003", "2003", "2003", "2003", "2003"), 
                     Unemp_percent = c(5.8, 5.9, 5.9, 6, 6.1, 6.3)), 
                row.names = 5:10, class = "data.frame")

# 匹配月份数字并生成Period列
df$month_num <- match(df$Month, month.abb)
df$Period <- sprintf("M%02d", df$month_num)
# 调整列顺序
df <- df[, c("Month", "Year", "Period", "Unemp_percent")]

方法2:tidyverse工具链实现(dplyr + lubridate)

借助lubridate的日期处理能力,更简洁地完成转换,适合批量数据场景:

适配情况1

library(dplyr)
library(lubridate)

unemployment <- unemployment %>%
  mutate(
    # 将Month列转换为日期格式
    date = dmy(paste0("01 ", Month)),
    # 提取月份数字并格式化
    Period = sprintf("M%02d", month(date))
  ) %>%
  select(Month, Period, Total) # 调整列顺序

适配情况2

df <- df %>%
  mutate(
    # 拼接Year、Month为完整日期
    date = ymd(paste(Year, Month, "01", sep = "-")),
    # 生成Period列
    Period = sprintf("M%02d", month(date))
  ) %>%
  select(Month, Year, Period, Unemp_percent)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:10:30