Search code examples
rlubridateperiod

Calculate age in years and months by adding period class objects together with lubridate in R


My data has a variable for baseline age, and a follow up variable with number of months since baseline observation. Both are numeric vectors with whole numbers only. I want to calculate age at follow up. When I parse these variables to period objects using lubridate and add them together I get results like 5 years 14 months. Ideally - I'd like this to be 6 years 2 months.

Example

library(dplyr)
library(lubridate)
library(magrittr)

set.seed(080617)
df <- 
  tibble(year = sample(20),
     month = sample(20))

df %<>% 
  mutate(year = years(year)) %>% 
  mutate(month = months(month)) %>%
  mutate(age = (year + month))
df

I have tried using df$age <- as.period(df$age, units = "years") to no avail.

Any suggestions?


Solution

  • This should get you the result you're looking for. I changed the column names to year.col and month.col, to make it easier to follow the logic

    library(dplyr)
    library(lubridate)
    library(magrittr)
    
    set.seed(080617)
    df <- 
      tibble(year.col = sample(20),
             month.col = sample(20))
    
    df %<>% 
      mutate(year.col = years(year.col)) %>% 
      mutate(month.col = months(month.col)) %>%
      mutate(age = year.col + years(month(month.col) %/% 12) + months(month(month.col) %% 12))