Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

Calculate number of days between two dates in 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))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
#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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...