2012-06-28 5 views
0

에 따라 차이는 I 시계열을R - 두 행 조건

dDate = 서열 (as.POSIXct ("2012년 1월 1일") as.POSIXct ("2012년 1월 10일을 "),"요일 ")
날짜 2012 년 01 월 03 일"2012-01-04 PST " 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 

값이 참인 간격을 알고 싶습니까?

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

답변

1

당신은 할 수 있습니다 :

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

nameing 조금 불행한 일이다. values (lengths[values])은 values 열이 아니지만 (rle) 개체의 요소입니다.

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]) 
+0

값이 -c (T, T, T, T, F, F, T, T, F, F) 인 경우 솔루션이 좋지만 작동하지 않습니다. 스위치를 계산하기 전에 값에 False를 추가하면 트릭이 수행됩니다. – 2sb