1

Trueまたは1の値を含む論理時系列で連続する領域を見つけるための便利でエレガントな既存のアプローチはありますか?フォームの要約を返すものを探しています:

Region_id               Start                Stop
        1 YYYY-MM-DD HH:MM:SS YYYY-MM-DD HH:MM:SS
        2 YYYY-MM-DD HH:MM:SS YYYY-MM-DD HH:MM:SS
        ... etc

入力例ts:

mins <- function (N, from = as.character(Sys.time()), cols = 1, by = 1) 
{
deltas <- seq(from = 0, by = 60 * by, length.out = N)
nacol <- matrix(data = NA, ncol = cols, nrow = N)
xts(x = nacol, order.by = strptime(from, format = "%Y-%m-%d %H:%M") + 
    deltas)
}

d <- mins(N=20,cols=1)
d[,1] <- F; d[5:12,1] <- T; d[14:20,1] <- T
d
                     [,1]
2012-12-18 20:48:00 FALSE
2012-12-18 20:49:00 FALSE
2012-12-18 20:50:00 FALSE
2012-12-18 20:51:00 FALSE
2012-12-18 20:52:00  TRUE
2012-12-18 20:53:00  TRUE
2012-12-18 20:54:00  TRUE
2012-12-18 20:55:00  TRUE
2012-12-18 20:56:00  TRUE
2012-12-18 20:57:00  TRUE
2012-12-18 20:58:00  TRUE
2012-12-18 20:59:00  TRUE
2012-12-18 21:00:00 FALSE
2012-12-18 21:01:00  TRUE
2012-12-18 21:02:00  TRUE
2012-12-18 21:03:00  TRUE
2012-12-18 21:04:00  TRUE
2012-12-18 21:05:00  TRUE
2012-12-18 21:06:00  TRUE
2012-12-18 21:07:00  TRUE

# so far for the _idealized_ input, now the function I am looking for to return data.frame 
# like this for the d object as above:
Region_id               Start                Stop
        1 2012-12-18 20:52:00 2012-12-18 20:59:00
        2 2012-12-18 21:01:00 2012-12-18 21:07:00

これはおそらくバイナリ信号処理の一般的なタスクであるため、検索する価値があります。もちろん、それは理想化されています。はじめに。現実はもっと複雑になります。

4

1 に答える 1

2

まず、を使用rleして隣接するブロックを検索し、次に各ブロックを区切るインジケーターを作成します。

r <- rle(coredata(d)[,1])
ind <- rep(seq_along(r$lengths), r$lengths)

これで、インジケーターを使用してxtsオブジェクトを分割し、隣接する各ブロックで最小/最大関数を実行できます。

s <- split(index(d), ind)
l <- lapply(s, function(x) data.frame(start=min(x), stop=max(x)))

次にrbind、上記の結果を1つのdata.frameにまとめ、region列を作成し、値のみをサブセットTRUE化して、累積合計を取得できます。タイムゾーンの違いにより私の時間は異なりますが、概念は正しいことに注意してください。

out <- do.call(rbind, l)
out$region <- r$values
out <- out[out$region,]
out$region <- cumsum(out$region)
out
#                 start                stop region
# 2 2012-12-18 20:45:00 2012-12-18 20:52:00      1
# 4 2012-12-18 20:54:00 2012-12-18 21:00:00      2
于 2012-12-18T21:07:31.287 に答える