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

R语言如何从日期向量中提取每个月第三周的最后一天

R日期向量筛选每月第三周最后一天方案

前置说明

默认周起始为周一,若需调整为周日,将下文week_start参数改为7即可。
你提供的日期向量仅包含工作日,最终筛选结果为每月第三周的最后一个工作日。

完整实现代码

# 加载依赖包
library(lubridate)
library(dplyr)

# 赋值你提供的日期向量
dates <- structure(c(18631L, 18632L, 18633L, 18634L, 18635L, 18638L, 18639L,
18640L, 18641L, 18642L, 18645L, 18646L, 18647L, 18648L, 18649L,
18651L, 18652L, 18653L, 18654L, 18655L, 18656L, 18659L, 18660L,
18661L, 18662L, 18663L, 18666L, 18667L, 18668L, 18669L, 18670L,
18673L, 18674L, 18675L, 18676L, 18677L, 18680L, 18681L, 18682L,
18683L, 18684L, 18687L, 18688L, 18689L, 18690L, 18691L, 18694L,
18695L, 18696L, 18697L, 18698L, 18701L, 18702L, 18703L, 18704L,
18705L, 18708L, 18709L, 18710L, 18711L, 18712L, 18715L, 18716L,
18717L, 18718L, 18722L, 18723L, 18724L, 18725L, 18726L, 18729L,
18730L, 18731L, 18732L, 18733L, 18736L, 18737L, 18738L, 18739L,
18740L, 18743L, 18744L, 18745L, 18746L, 18747L, 18750L, 18751L,
18752L, 18753L, 18754L, 18757L, 18758L, 18759L, 18760L, 18761L,
18764L, 18765L, 18766L, 18767L, 18768L), class = c("IDate", "Date"))

# 转换为通用Date格式
dates <- as.Date(dates)

# 构造数据框计算核心指标
date_df <- tibble(date = dates) %>%
  mutate(
    # 提取年月分组标识
    year_month = floor_date(date, "month"),
    # 当月第一天的周序(周一是1,周日是7)
    first_wday = wday(year_month, week_start = 1),
    # 日期在当月的天数
    mday = mday(date),
    # 计算日期属于当月的第几周
    month_week = (mday + first_wday - 2) %/% 7 + 1
  )

# 筛选每月第三周的最后一天
third_week_last <- date_df %>%
  filter(month_week == 3) %>%
  group_by(year_month) %>%
  filter(date == max(date)) %>%
  pull(date)

# 输出结果
print(third_week_last)

无dplyr的基础包实现方案

若不想引入dplyr依赖,可使用以下代码实现相同效果:

library(lubridate)
dates <- as.Date(dates)
year_month <- floor_date(dates, "month")
first_wday <- wday(year_month, week_start = 1)
mday_val <- mday(dates)
month_week <- (mday_val + first_wday - 2) %/% 7 + 1
# 筛选第三周日期
third_week_dates <- dates[month_week == 3]
third_week_ym <- floor_date(third_week_dates, "month")
# 按年月取最大日期
third_week_last <- tapply(third_week_dates, third_week_ym, max, simplify = FALSE) %>% unname() %>% do.call("c", .)
print(third_week_last)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 14:06:04