2016-11-08 36 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")