Calculate number of days between two dates in r

Solution 1:

#Using dplyr package
library(dplyr)
df1 %>%  # your dataframe
mutate(BETWEEN0=as.numeric(difftime(DATE,lag(DATE,1))),BETWEEN=ifelse(is.na(BETWEEN0),0,BETWEEN0),FIRST=cumsum(as.numeric(BETWEEN)))%>%
select(-BETWEEN0)
            DATE BETWEEN FIRST
    1 2013-07-08       0     0
    2 2013-08-01      24    24
    3 2013-08-30      29    53
    4 2013-10-23      54   107
    5 2013-12-16      54   161
    6 2015-12-16     730   891

Solution 2:

This will get you what you want:

d <- as.Date(DATA$DATE, format="%m/%d/%Y")

first <- c()
for (i in seq_along(d))
    first[i] <- d[i] - d[1]

between <- c(0, diff(d))

This uses the as.Date() function in the base package to cast the vector of string dates to date values using the given format. Since you have dates as month/day/year, you specify format="%m/%d/%Y" to make sure it's interpreted correctly.

diff() is the lagged difference. Since it's lagged, it doesn't include the difference between element 1 and itself, so you can concatenate a 0.

Differences between Date objects are given in days by default.

Then constructing the output dataframe is simple:

RESULTS <- data.frame(DATE=DATA$DATE, FIRST=first, BETWEEN=between)