Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending difftime() to include months and years

Tags:

r

I can get the time since x with difftime, but only up to week intervals.

> difftime(Sys.Date(), "1977-04-05")
# Time difference of 13655.67 days
> difftime(Sys.Date(), "1977-04-05", units = "weeks")
# Time difference of 1950.81 weeks

Other than calculating it manually, is there a function to get the months and years since x?

I've looked at this question convert difftime time to years, months and days, but it was asked and answered over two years ago and I thought there may be some new stuff out there now.

The reason I'd like to get this information is to add it to this useless function

> timeSinceBirth <- function(dob) 
  {
      today <- Sys.Date()
      s <- sapply(list(NULL, "weeks"), function(x) {
          difftime(today, dob, units = x)
      })
      setNames(s, c("days", "weeks"))
  }
> timeSinceBirth("1977-04-05")
#     days    weeks 
# 13655.67  1950.81 

I'd like the result to have months and years included after weeks

like image 964
Rich Scriven Avatar asked Feb 13 '23 04:02

Rich Scriven


1 Answers

You can use a sequence. So something like:

timeSinceBirth <- function(dob) 
{
  today <- Sys.Date()
  s <- sapply(list("days", "weeks", "months", "years"), function(x) {
    (length(seq(as.Date(dob), Sys.Date(), x)) - 1)
  })
  setNames(s, c("days", "weeks", "months", "years"))
}

> timeSinceBirth("1977-04-05")
days  weeks months  years 
13657   1951    448     37 
like image 156
jdharrison Avatar answered Feb 14 '23 17:02

jdharrison