2016-05-23 98 views
1

我有一個長格式的數據集作爲開始和結束日期。爲每個ID你會看到多個開始和結束日期。 我需要找到第一個結束日期和第二個開始日期之間的區別。我不知道如何使用兩行來計算差異。任何幫助表示讚賞。查找長格式日期之間的差異

df=data.frame(c(1,2,2,2,3,4,4), 
       as.Date(c("2010-10-01","2009-09-01","2014-01-01","2014-02-01","2009-01-01","2013-03-01","2014-03-01")), 
       as.Date(c("2016-04-30","2013-12-31","2014-01-31","2016-04-30","2014-02-28","2013-05-01","2014-08-31"))); 
names(df)=c('id','start','end') 

我的輸出應該是這樣的:

df$diff=c(NA,1,1,NA,NA,304, NA) 
+0

@latemail這是正確的。我編輯了我的問題 –

回答

1

下面是採用了時下流行dplyr包的替代:

library(dplyr) 
df %>% 
    group_by(id) %>% 
    mutate(diff = difftime(lead(start), end, units = "days")) 
#  id  start  end  diff 
# (dbl)  (date)  (date) (dfft) 
# 1  1 2010-10-01 2016-04-30 NA days 
# 2  2 2009-09-01 2013-12-31 1 days 
# 3  2 2014-01-01 2014-01-31 1 days 
# 4  2 2014-02-01 2016-04-30 NA days 
# 5  3 2009-01-01 2014-02-28 NA days 
# 6  4 2013-03-01 2013-05-01 304 days 
# 7  4 2014-03-01 2014-08-31 NA days 

可以在as.numeric包裹diff如果你想。

1

下面是基礎R的嘗試,我覺得你想要做什麼:

df$diff <- NA 
split(df$diff, df$id) <- by(df, df$id, FUN=function(SD) c(SD$start[-1], NA) - SD$end) 

df 
# id  start  end diff 
#1 1 2010-10-01 2016-04-30 NA 
#2 2 2009-09-01 2013-12-31 1 
#3 2 2014-01-01 2014-01-31 1 
#4 2 2014-02-01 2016-04-30 NA 
#5 3 2009-01-01 2014-02-28 NA 
#6 4 2013-03-01 2013-05-01 304 
#7 4 2014-03-01 2014-08-31 NA 

另外,在data.table這將是:

setDT(df)[, diff := shift(start,n=1,type="lead") - end, by=id] 
0

再次與基礎R,你可以做到以下幾點:

df$noofdays <- as.numeric(as.difftime(df$end-df$start, units=c("days"), format="%Y-%m-%d")) 
+0

這並沒有給出正確的結果。 – thelatemail

相關問題