2016-11-08 37 views
0

我有以下內容查找天中的R

Date  Comments failure #ofdays 
2014-10-25 abc  0 
2014-10-30 def  1 
2014-11-10 ghi  0 
2014-11-15 lmo  0 

等的數據幀....(它有許多更多的行)。 我試圖寫R代碼來實現填充循環移位#of天列如下:

Date  Comments failure #ofdays 
2014-10-25 abc  0   0 
2014-10-30 def  1   0 
2014-11-10 ghi  0   10 
2014-11-15 lmo  0   15 

所以,基本上,如果出現故障,該天數應重置爲0。如果不是,它應該保持自上次失敗後的累積天數。 我試圖

no.of.days<-ifelse(failure==1,0, difftime((Date),lag(Date,1,default=0))+lag(no.of.days,1) 

,但我得到的垃圾值輸出。它給了我30,000+天的輸出。 但是,如果我爲了測試目的而在兩個值之間運行difftime,我正確得到了#天。 難道你們可以看一看,讓我知道我錯過了什麼嗎? 在此先感謝!

回答

2

你可以試試:

ave(as.numeric(df$Date),cumsum(df$failure!=0),FUN=function(x) x-x[1]) 
#[1] 0 0 11 16 

請注意,2014-10-30和2014年11月10日之間有11天(而不是10表明這個問題)。

數據

df<-structure(list(Date = structure(c(16368, 16373, 16384, 16389), class = "Date"), 
    Comments = c("abc", "def", "ghi", "lmo"), failure = c(0L, 
    1L, 0L, 0L)), .Names = c("Date", "Comments", "failure"), row.names = c(NA, 
-4L), class = "data.frame")