Rich Scriven
Rich Scriven

Reputation: 99331

Extending difftime() to include months and years

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

Upvotes: 4

Views: 1072

Answers (1)

jdharrison
jdharrison

Reputation: 30425

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 

Upvotes: 8

Related Questions