Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate number of days between two dates in r

Tags:

r

I need to calculate the number of days elapsed between multiple dates in two ways and then output those results to new columns: i) number of days that has elapsed as compared to the first date (e.g., RESULTS$FIRST) and ii) between sequential dates (e.g., RESULTS$BETWEEN). Here is an example with the desired results. Thanks in advance.

library(lubridate)

DATA = data.frame(DATE = mdy(c("7/8/2013",  "8/1/2013", "8/30/2013", "10/23/2013", 
                                   "12/16/2013", "12/16/2015")))

RESULTS  = data.frame(DATE = mdy(c("7/8/2013",  "8/1/2013", "8/30/2013", "10/23/2013", 
                                       "12/16/2013", "12/16/2015")), 
                  FIRST = c(0, 24, 53, 107, 161, 891), BETWEEN = c(0, 24, 29, 54, 54, 730))
like image 921
Vesuccio Avatar asked Feb 27 '15 16:02

Vesuccio


People also ask

Can you subtract two dates in R?

In R programming, difference between two dates can be determined by using basic function julian() and passing date object as the parameter in the function.

How do you calculate elapsed time in R?

The tic() function starts the timer and toc() function ends the timer, elapsed time gets measured for whatever code is placed between these function calls.

How do I change the date format in R?

To format = , provide a character string (in quotes) that represents the current date format using the special “strptime” abbreviations below. For example, if your character dates are currently in the format “DD/MM/YYYY”, like “24/04/1968”, then you would use format = "%d/%m/%Y" to convert the values into dates.


1 Answers

#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
like image 51
Metrics Avatar answered Oct 14 '22 10:10

Metrics