Working with dates in any programming language can be incredibly stressful. Luckily for us, there is an easy way to convert dates from a Date/Time class like POSIXct to a Date class in R using modify_if from the Tidyverse.
new_data <- orig_data %>% modify_if(is.POSIXct, as.Date)
*Blue text is information you’ll need to sub out for your own
There two date/time classes in R, POSIXct and POSIXlt, have subtle differences that I won’t go into here. If you’d like to know more, this article from UC Berkeley gives a great overview. The main thing to note is that they store dates in the yyyy-mm-dd hh:mm:ss format, which can be a problem if you need your dates in a format like yyyy-mm-dd or mm/dd/yyyy. There’s a super quick way to update all of the Date/Time variables in a data frame using the purrr modify_if function:
Example
To provide a visual, we’ll walk through an example of converting dates from Date/Time to Date below.
First, we’ll load the packages we want to work with:
#load packages
suppressPackageStartupMessages(library(pacman))
pacman::p_load(tidyverse, lubridate)
Then, we can create some example data. We can create ‘birthday’ as class POSIXct and ‘party’ as class POSIXlt.
#example data
birthday <- as.POSIXct("1990-01-09 01:30:00")
party <- as.POSIXlt("2023-01-09 20:00:00")
dt_dates <- tibble(birthday = birthday,
party = party)
Finally, we’ll use the modify_if function to convert one or both classes to Dates.
#convert only POSIXct
new_dates1 <- dt_dates %>% modify_if(is.POSIXct, as.Date)
#convert both POSIXct and POSIXlt
new_dates2 <- dt_dates %>% modify_if(is.POSIXct, as.Date) %>% modify_if(is.POSIXlt, as.Date)
When we select the dropdown arrow on our dataset, we can see that both variables have now been converted to a date class: