[R] how to calculate time interval between dates

David Winsemius dwinsemius at comcast.net
Sat Aug 1 14:00:25 CEST 2009


On Jul 31, 2009, at 4:46 PM, liujb wrote:

>
> Dear R users:
>
> I have a vector of dates as follows:
> t <- c("2007-01-05", "2007-05-14", "2007-12-28", "2008-01-09",  
> "2008-04-24",
> "2009-02-14")
>
> I'd like to calculate number of days between those dates (time  
> interval).
> How to do it?

That is not a vector of dates, but rather a character vector.
Observe:

  t <- c("2007-01-05", "2007-05-14", "2007-12-28", "2008-01-09",  
"2008-04-24",
  "2009-02-14")
  class(t)
# [1] "character"
  diff(t)
#Error in r[i1] - r[-length(r):-(length(r) - lag + 1)] :
#  non-numeric argument to binary operator

Try:

  t2 <- as.Date(t)
  class(t2)
#[1] "Date"
  t2
# [1] "2007-01-05" "2007-05-14" "2007-12-28" "2008-01-09" "2008-04-24"  
"2009-02-14"
  ?diff
  diff(t2)
#Time differences in days
#[1] 129 228  12 106 296


>

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list