Here is my example data, and I want to customise week_start by year in wday
function from lubridate
package
mydate <- data.frame(Date = c("13/09/2021", "13/09/2020", "13/09/2019", "13/09/2018"))
For instance, the start of the week will be year %% 7
. But I got the following error when I run my code
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))
I think I need to use the map
function from purrr
. I have tried few times, but it didn't work.
Thanks a lot.
You may use map2_chr
to have a custom week_start
for every Date
based on year
value.
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