2014-04-02 66 views
3

我有一個時間序列的邏輯數據。我試圖找到時間:(a)當時的邏輯是錯誤的; (b)前三個時期的邏輯是錯誤的; (c)以下兩個時期的邏輯是錯誤的。例如在以下數據框中,只有時間5符合標準。前瞻性時間序列濾波器

example <- structure(list(time = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), raining = c(TRUE, 
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE)), .Names = c("time", 
"raining"), row.names = c(NA, -10L), class = "data.frame") 

我可以很容易地查看當前的時間和前三款使用過濾器

example$filtered <- filter(example[,"raining"], c(1,1,1,1), sides = 1) == 0 

,但我無法弄清楚如何讓它也期待着。也許使用sides = 2和一個不同的過濾器集合?任何幫助表示讚賞。

回答

3

我想你可以通過尋找具有6個前一分等於0點重新制定問題再取2了你的矢量版本從索引獲得理想的結果。

000 0 00 <---> 00000 0 
    --- _ ++  ----- _ 

這裏使用zoo包解決方案:

library(zoo) 
dt = zoo(example$raining,order.by=example$time) 
res <- rollsumr(dt, 6) ## as commented below 
index(res[res==0])-2 
[1] 5 

使用filter,你可以這樣做:

filter(example[,"raining"], rep(1,6), sides = 1)==0 
+1

+1更簡單的方式來看待這個問題! – Henrik

+0

同意。像往常一樣,我有一個邏輯問題,而不是編程問題!謝謝 –

+0

請注意,'rollapplyr'行可寫爲'res < - rollersumr(dt,6)'。 –

2

您可以創建偏移使用功能leadlag封裝dplyr

library(dplyr) 
m <- cbind(sapply(3:1, function(x) lag(rain, x)), # preceeding three 
      rain,         # current 
      sapply(1:2, function(x) lead(rain, x))) # following two 

# find row with all FALSE 
which(rowSums(m, na.rm = TRUE) == 0) 
# [1] 5