0

我有一个时间序列:

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 PST"

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

我想知道这些值是真实的时间间隔。

预期结果:

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

2 回答 2

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])
于 2012-06-28T16:33:31.597 回答
1

你可以做:

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

取名有点可惜。valuesinlengths[values]不是你的valuescol,而是对象的values元素rle

于 2012-06-28T16:35:12.063 回答