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

如何为R语言数据框中仅含年份的日期段补全月份?

补全日期段中的缺失月份

首先看原始数据:

d1 <- data.frame(id = c(1,2,3),
                 date1 = c("2014-2018","Jun 2009-2010","Jan 2009-Aug 2010"), 
                 date2 = c("Feb 2016-2018","2014-Dec 2018","Oct 2013-Dec 2018"))

输出:

#   id             date1             date2
# 1  1         2014-2018     Feb 2016-2018
# 2  2     Jun 2009-2010     2014-Dec 2018
# 3  3 Jan 2009-Aug 2010 Oct 2013-Dec 2018

可以用正则表达式结合gsub函数批量处理日期列,对应规则:

  • 对于-前仅含年份的部分,在年份前添加Jan
  • 对于-后仅含年份的部分,在年份前添加Dec

解决方案代码

# 定义日期补全函数
fill_month <- function(x) {
  # 补全-前的纯年份:匹配开头的四位数字(无前置月份)
  x <- gsub("^([0-9]{4})-", "Jan \\1-", x)
  # 补全-后的纯年份:匹配结尾的四位数字(无后置月份)
  x <- gsub("-([0-9]{4})$", "-Dec \\1", x)
  return(x)
}

# 应用到date1和date2列
d1[, c("date1", "date2")] <- lapply(d1[, c("date1", "date2")], fill_month)

处理后的数据:

print(d1)

输出:

#   id             date1             date2
# 1  1 Jan 2014-Dec 2018 Feb 2016-Dec 2018
# 2  2 Jun 2009-Dec 2010 Jan 2014-Dec 2018
# 3  3 Jan 2009-Aug 2010 Oct 2013-Dec 2018

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:30:56