2016-04-21 57 views
0

如何在條件爲TRUE時獲得該行,並在它後面N行?如果N行中的任何一行的條件爲TRUE,請重新啓動計數。也爲每個組執行此操作。R data.table當條件爲TRUE時,找到下N行

dt = data.table(a = rep(c("a","b","c"), each = 5), b = 1:15) 
dt[, condition := b%%4 == 0] 
> dt 
    a b condition **desiredOutcome** 
1: a 1  FALSE   FALSE 
2: a 2  FALSE   FALSE 
3: a 3  FALSE   FALSE 
4: a 4  TRUE   TRUE 
5: a 5  FALSE   TRUE 
6: b 6  FALSE   FALSE 
7: b 7  FALSE   FALSE 
8: b 8  TRUE   TRUE 
9: b 9  FALSE   TRUE 
10: b 10  FALSE   TRUE 
11: c 11  FALSE   FALSE 
12: c 12  TRUE   TRUE 
13: c 13  FALSE   TRUE 
14: c 14  FALSE   TRUE 
15: c 15  FALSE   FALSE 

desiredOutcomea柱基於N=2和基團。得到這個的最好方法是什麼?

+0

'DT [,移(狀態,0:N),由=一]'近的作品,但它是非常難行總和轉移 – jf328

回答

3

發現總結的shift的結果,即向量的列表的方式。

dt[, desiredOutcome := Reduce('+', shift(con, 0:2, fill = 0)), by = a]

1

我們可以嘗試

dt[dt[, {i1 <- which(condition); .I[i1:pmin((i1+2), .N)]} , a]$V1, 
    desiredOutcome:= TRUE][is.na(desiredOutcome), desiredOutcome := FALSE][] 
# a b condition desiredOutcome 
# 1: a 1  FALSE   FALSE 
# 2: a 2  FALSE   FALSE 
# 3: a 3  FALSE   FALSE 
# 4: a 4  TRUE   TRUE 
# 5: a 5  FALSE   TRUE 
# 6: b 6  FALSE   FALSE 
# 7: b 7  FALSE   FALSE 
# 8: b 8  TRUE   TRUE 
# 9: b 9  FALSE   TRUE 
#10: b 10  FALSE   TRUE 
#11: c 11  FALSE   FALSE 
#12: c 12  TRUE   TRUE 
#13: c 13  FALSE   TRUE 
#14: c 14  FALSE   TRUE 
#15: c 15  FALSE   FALSE 
+0

對不起的輸出,我選擇的例子可能是誤導。我不想要TRUE直到結束,但接下來N行。我修改了這個例子。 – jf328

+0

謝謝!但是,如果有兩行滿足一個組中的條件,即'which(condition)'返回一個向量,則該操作失敗 – jf328

+0

@ jf328此解決方案基於您提供的示例。 – akrun