Home > other >  Is it possible to use difftime function in R with years ONLY (i.e. no DD/MM)?
Is it possible to use difftime function in R with years ONLY (i.e. no DD/MM)?

Time:10-21

For example:

Year A Year B
1990 2021
1980 2021

Thanks in advance.

CodePudding user response:

It depends of what you expect.

If you only want to use the difftime() function with date objects composed only of years (as below), it will work (it will set the day and month to the ones of today for the calculation).

> a = as.Date("2021", format("%Y"))
> b = as.Date("2010", format("%Y"))
> difftime(a,b)
Time difference of 4018 days

But if you want to get the difference in year, it is not possible, as the function documentation clearly state that the return value unit must be: units = c("auto", "secs", "mins", "hours", "days", "weeks")

You might find better way to handle date/time data with the lubridate package.

CodePudding user response:

difftime requests a date object to be used, I tried reproducing this using only years but was unable to.

Why not simply use absolute value (abs())If you're only interested in year difference?

as an example so you can see the difference added to a new column:

Year_A <- c(1990, 1980)
Year_B <- c(2021, 2021)

df <- data.frame(Year_A, Year_B)

df$diff <- abs(Year_A - Year_B)

P.S I noticed the answer above me was added while I was answering and I can't comment to it due to low rep, i see you can't use "years" as a unit value there, the biggest one being weeks, but you can manipulate that from days/weeks to years if that's what you're after.

  •  Tags:  
  • r
  • Related