Skip to content
R for the Rest of Us Logo

R in 3 Months (Fall 2022)

{lubridate} for working with dates and times

Transcript

Click on the transcript to go to that point in the video. Please note that transcripts are auto generated and may contain minor inaccuracies.

The {lubridate} package is part of the tidyverse and provides awesome tools for manipulating, creating and working with both dates and times. Charlie's recorded the short video lesson on the topic below, and there's a dedicated chapter in the R for Data Science book.

Here's a copy of the code that Charlie used in her video

library(tidyverse)
library(haven)
library(lubridate)

museum_data <- read_spss("Corning Museum of Glass - Glass of the Architects TT Data 2018-10-30.sav")

museum_data %>%
  select(starts_with("time")) %>% 
  mutate(time_A = duration(time_A))

museum_data %>%
  select(starts_with("time")) %>% 
  mutate(across(starts_with("time"),
                ~ duration(.))) %>% 
  select(1:4) %>% 
  mutate(time_total_a_thru_c = time_A + time_B + time_C,
         time_total_a_thru_c = as.numeric(time_total_a_thru_c, "hours"))
         

# Make shipping data -------------------------------------------------------------

set.seed(1)
shipping_data <- tibble(
  order_date = sample(seq(ymd('2012-04-07'),ymd('2020-03-22'), by = 'day'), 50)
) %>% 
  mutate(shipping_date = order_date + sample(days(5:10), 50, replace = TRUE)) %>% 
  mutate(receive_date = shipping_date + sample(days(10:50), 50, replace = TRUE)) %>% 
  mutate(id = row_number()) %>% 
  mutate(order_year = year(order_date),
         order_month = month(order_date),
         order_day = day(order_date)) %>% 
  select(id, order_year, order_month, order_day, shipping_date, receive_date)


# Wrangle shipping date ---------------------------------------------------

shipping_data %>% 
  mutate(order_date = make_date(order_year, order_month, order_day)) %>% 
  select(id, order_date, shipping_date, receive_date) %>% 
  mutate(total_order_time = receive_date - order_date,
         total_order_time = as.numeric(total_order_time, "days"))

Have any questions? Put them below and we will help you out!

You need to be signed-in to comment on this post. Login.

Course Content

142 Lessons