R lubridate 按年自定义 week_start

R lubridate customise week_start by year

这是我的示例数据,我想在 lubridate

wday 函数中按年份自定义 week_start
mydate <- data.frame(Date = c("13/09/2021", "13/09/2020", "13/09/2019", "13/09/2018"))

例如,一周的开始时间是 year %% 7。但是当我 运行 我的代码

时出现以下错误

numerical expression has 4 elements: only the first used

library(lubridate)
library(dplyr)

mydate2 <- mydate %>%
  mutate(Date = ymd(as.Date(as.factor(Date), format = "%d/%m/%Y")),
         years = year(Date),
         days = wday(Date, label = TRUE, week_start = years %% 7)) 

我想我需要使用 purrr 中的 map 函数。试了几次都没用。

非常感谢。

您可以使用 map2_chr 为每个 Date 基于 year 值的自定义 week_start

library(dplyr)
library(lubridate)

mydate %>%
  mutate(Date = as.Date(Date, format = "%d/%m/%Y"),
         years = year(Date),
         days = map2_chr(Date, years, 
                  ~as.character(wday(.x, label = TRUE, week_start = .y %% 7))))


#        Date years days
#1 2021-09-13  2021  Mon
#2 2020-09-13  2020  Sun
#3 2019-09-13  2019  Fri
#4 2018-09-13  2018  Thu