I am trying to run a piece of code to calculate the number of days between 2 dates, whenever a status is changed to the value 1.
below is a sample of the data frame:
I can calculate using the following code between 2 dates no problem, it is when there is a status change between each change i need to calculate the number of days.
df$Date2_Date1 <- difftime(df$Date2,df$Date1, units = c("hours"))
With the provided dataframe (one alteration: added an / in the 4th date) and one edit in the previous code (unit instead of unist):
library(dplyr)
id= c(1,1,1,1,1,2,2,2,2,3,3,3,3)
status = c(0,0,0,1,0,0,0,1,0,0,0,0,0)
date =c('08/01/2017','09/01/2017','10/01/2017','11/01/2017',
'13/01/2017','16/01/2017','17/01/2017','18/01/2017',
'19/01/2017','20/01/2017','21/01/2017','23/01/2017', '24/01/2017')
data <-data.frame(id,status,date)%>%
mutate(date=as.Date(date,"%d/%m/%Y"))
data%>%group_by(id,status)%>%
summarise(date = min(date))%>%
summarise(min = min(date),
max = max(date),
n = n(),
Diff = difftime(max,min,unit=c("hours")),
Diff = ifelse(n==2, Diff,NA))
gives
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.