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

如何用向量条件替代dplyr case_when逐行代码 实现日期匹配所属周起始周日

解决方案

直接使用lubridate内置的日期取整函数即可实现需求,无需编写冗余的分支判断,也无需预先生成周区间列表,可直接适配任意年限的日期数据:

library(lubridate)
library(tidyverse)

# 生成测试日期数据
sunday_first <- ymd("2021/10/31")
list_days <- (sunday_first + days(0:30)) %>% enframe(value = "date")

# 计算周归属
list_days <- list_days %>%
  mutate(
    # week_start=1 指定周起始为周日
    week_sunday = floor_date(date, unit = "week", week_start = 1),
    "Week of" = paste0("Week of ", format(week_sunday, "%m/%d/%Y"))
  )

如果你的场景确实需要匹配预定义的周区间列表list_weeks,可以用findInterval函数批量匹配,无需逐行写case_when条件:

list_weeks <- sunday_first + weeks(0:4)

list_days %>%
  mutate(
    week_index = findInterval(date, list_weeks),
    "Week of" = list_weeks[week_index]
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:36:04