I'm trying to combine mutate, across, and as_date, including the format
argument in as_date. This is resulting in all NA
values, as shown below.
library(tidyverse)
library(tis)
holidays(2023) %>%
data.frame() %>%
set_names('holiday_date') %>%
rownames_to_column() %>%
pivot_wider(names_from = rowname,values_from = holiday_date) %>%
mutate(across(everything(), as.character)) %>%
mutate(across(everything(),
#as_date # WORKS
~as_date(.,format="yyyymmdd") # DOESN'T WORK
))
This results in
# A tibble: 1 × 10
NewYears MLKing GWBirthday Memorial Juneteenth Independence Labor Columbus Thanksgiving
<date> <date> <date> <date> <date> <date> <date> <date> <date>
1 NA NA NA NA NA NA NA NA NA
# ℹ 1 more variable: Christmas <date>
If I swap the commented out as_date
line (labelled "WORKS
") for the ~as_date
line ("DOESN'T WORK
"), I get the expected result, sans the desired formatting:
# A tibble: 1 × 10
NewYears MLKing GWBirthday Memorial Juneteenth Independence Labor Columbus Thanksgiving
<date> <date> <date> <date> <date> <date> <date> <date> <date>
1 2023-01-02 2023-01-16 2023-02-20 2023-05-29 2023-06-19 2023-07-04 2023-09-04 2023-10-09 2023-11-23
# ℹ 1 more variable: Christmas <date>
Can someone tell me what is going wrong here and how to obtain the desired result?
when you used pivot_wider()
and then applied mutate(across(...))
, the column types got converted to character format, hence the problem with the date conversion with as_date
with the format argument.
instead, use mutate(across(...))
directly after pivot_wider()
to convert the columns to character, and then use another mutate(across(...))
to convert them to dates. you can specify your own desired format.
holidays(2023) %>%
data.frame() %>%
set_names('holiday_date') %>%
rownames_to_column() %>%
pivot_wider(names_from = rowname, values_from = holiday_date) %>%
mutate(across(everything(), as.character)) %>%
mutate(across(everything(), as_date)) %>% # Convert to dates without format
mutate(across(everything(),
~as_date(., format = "%Y-%m-%d"))) # Convert to dates with the desired format