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

如何在R语言中获取月末最后一个工作日及上月末最后一个工作日

嘿,这两个日期处理的需求在日常数据分析或者业务场景里真的挺常见的,我给你分享两种实现思路——一种是用专门的工作日处理包简化操作,另一种是用基础R结合lubridate手动实现,你可以按需选择~

1. 获取当月的最后一个工作日

方法一:用bizdays包(推荐,支持自定义节假日)

bizdays包专门用来处理工作日相关的计算,还能自定义节假日日历,非常灵活。

首先安装并加载包:

install.packages("bizdays")
library(bizdays)

然后设置默认的工作日历(默认排除周六、周日):

# 创建只排除周末的工作日历
create.calendar("weekdays_cal", weekdays = c("saturday", "sunday"))

接下来就可以快速获取当月最后一个工作日了:

# 获取当月的最后一天
last_day_of_month <- ceiling_date(Sys.Date(), "month") - days(1)
# 自动调整为最近的工作日(如果最后一天是周末就往前推)
last_workday_current_month <- adjust.previous(last_day_of_month, "weekdays_cal")

# 输出结果
last_workday_current_month

方法二:基础R + lubridate(无需额外安装工作日包)

如果不想安装新包,也可以手动判断当月最后一天的星期,再调整日期:

library(lubridate)

get_last_workday_current_month <- function() {
  # 获取当月最后一天
  last_day <- ceiling_date(Sys.Date(), "month") - days(1)
  # 用week_start=1让周一为每周第1天,周日为第7天
  weekday_num <- wday(last_day, week_start = 1)
  
  # 根据星期数调整日期
  if (weekday_num == 6) { # 周六,往前推1天
    last_day - days(1)
  } else if (weekday_num == 7) { # 周日,往前推2天
    last_day - days(2)
  } else { # 工作日,直接返回
    last_day
  }
}

# 调用函数获取结果
get_last_workday_current_month()
2. 根据当前日期获取上月的最后一个工作日

同样提供两种思路,以你举的例子(当前日期2018-01-05,期望结果2017-12-29)来测试:

方法一:用bizdays包

library(bizdays)
library(lubridate)

# 还是用之前创建的工作日历
create.calendar("weekdays_cal", weekdays = c("saturday", "sunday"))

get_last_workday_last_month <- function(current_date = Sys.Date()) {
  # 获取上月的最后一天
  last_day_last_month <- floor_date(current_date, "month") - days(1)
  # 调整为最近的工作日
  adjust.previous(last_day_last_month, "weekdays_cal")
}

# 测试例子
get_last_workday_last_month(as.Date("2018-01-05"))
# 输出:"2017-12-29",符合预期

方法二:基础R + lubridate

library(lubridate)

get_last_workday_last_month <- function(current_date = Sys.Date()) {
  # 获取上月最后一天
  last_day_last_month <- floor_date(current_date, "month") - days(1)
  weekday_num <- wday(last_day_last_month, week_start = 1)
  
  # 调整日期
  if (weekday_num == 6) {
    last_day_last_month - days(1)
  } else if (weekday_num == 7) {
    last_day_last_month - days(2)
  } else {
    last_day_last_month
  }
}

# 测试例子
get_last_workday_last_month(as.Date("2018-01-05"))
# 输出:"2017-12-29",完美匹配需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:15:39