::as.yearmon(c("2020-10-01", "2021-06-02", "2021-5-02", "2022-11-5")) zoo
Dates in R, the easy way
Today’s #rstats “this was easier than I thought” moment:
zoo::as.yearmon()
Working on a table where the headers are originally formatted “2023-01-27” and we want it to format headers as “Jan 2023”.
Turns out, it’s easier than I thought (zoo accepts 01 or 1 for month)!
Now for the table, we’re using {flextable}
to format things. My first try of using zoo::as.yearmon()
as is, but that didn’t quite go to plan.
Instead, pasting the outcome worked: paste(zoo::as.yearmon(my_dates))
Voila!
Table with original formatting of dates
%>%
my_data flextable() %>%
# more_flextable_formatting
Table with dates formatted as decimals (e.g. 2020.333, 2020.75, …)
%>%
my_data flextable() %>%
delete_part(part = "header") %>%
add_header_row(values = c("", zoo::as.yearmon(my_dates))) %>%
# more_flextable_formatting
Table with dates formatted as desired (e.g. May 2020, Oct 2020, …)
%>%
my_data flextable() %>%
delete_part(part = "header") %>%
add_header_row(values = c("", paste(zoo::as.yearmon(my_dates)))) %>%
# more_flextable_formatting
Reuse
Citation
For attribution, please cite this work as:
Thompson, Cara. 2023. “Dates in R, the Easy Way.” January
27, 2023. https://www.cararthompson.com/posts/2023-01-27-todays-rstats-this-was-easier/.