Search code examples
pythonrdifftime

How do I calculate age as years, months, and days in R?


I want to calculate age as years, months, and days.

I can do it with python's dateutil package

from dateutil.relativedelta import relativedelta
from datetime import date
rel_obj = relativedelta(date(2008,8,6),date(2004,1,1))
rel_obj.years, rel_obj.months, rel_obj.days

(4, 7, 5)

I used difftime function in R

o <- difftime(date("2008-8-6") , date("2004-1-1"))
o$ : has no attribute like relativedelta's

How do I format difftime object like in python ?


Solution

  • Here is a solution with package lubridate, a standard R package to deal with dates and times.

    library(lubridate)
    #> Loading required package: timechange
    #> 
    #> Attaching package: 'lubridate'
    #> The following objects are masked from 'package:base':
    #> 
    #>     date, intersect, setdiff, union
    
    d1 <- as.Date("2004-1-1")
    d2 <- as.Date("2008-8-6")
    
    diffdays2ymd <- function(x, y, ...) {
      tmp <- x |>
        lubridate::interval(y) |> 
        lubridate::as.period()
      y <- lubridate::year(tmp)
      m <- lubridate::month(tmp)
      d <- lubridate::day(tmp)
      c(year = y, month = m, day = d)
    }
    diffdays2ymd(d1, d2)
    #>  year month   day 
    #>     4     7     5
    

    Created on 2022-12-13 with reprex v2.0.2