R - 两行之间的差异取决于条件

时间:2012-06-28 16:21:19

标签: r time-series

我有时间序列

  

dDate = seq(as.POSIXct(“2012/1/1”),as.POSIXct(“2012/1/10”),“day”)
  dDate
       [1]“2012-01-01 PST”“2012-01-02 PST”“2012-01-03 PST”“2012-01-04 PST”“2012-01-05 PST”“2012-01-06 PST “”2012-01-07 PST“”2012-01-08 PST“”2012-01-09 PST“      [10]“2012-01-10太平洋标准时间”

values <- c(F,T,T,T,F,F,T,T,F,F)
> dframe <- data.frame(time=dDate,values=values)  
> dframe
  time values
  1  2012-01-01  FALSE 
  2  2012-01-02   TRUE
  3  2012-01-03   TRUE
  4  2012-01-04   TRUE 
  5  2012-01-05  FALSE  
  6  2012-01-06  FALSE  
  7  2012-01-07   TRUE  
  8  2012-01-08   TRUE   
  9  2012-01-09  FALSE 
  10 2012-01-10  FALSE

我想知道值为真的时间间隔?

  Expected Result
  StartTime          Diff(day)
  2012-01-02         3
  2012-01-07         2 

2 个答案:

答案 0 :(得分:1)

这个怎么样?

> secsPerDay <- 24 * 60 * 60
> switch     <- c(NA, diff(values))
> startTime  <- dDate[switch==1]
> endTime    <- dDate[switch==-1]
> period     <- (as.numeric(endTime) - as.numeric(startTime)) / secsPerDay
> result     <- data.frame(startTime=startTime[-1], period=period[-1])

答案 1 :(得分:1)

你可以这样做:

with(dframe, data.frame(StartTime = time[diff(c(FALSE, values)) == 1], 
                        Days = with(rle(values), lengths[values])))

这个名字有点不幸。 values中的lengths[values]不是values col,而是values对象的rle元素。