0
問題:我想使用dplyr
或ave
做到以下幾點:如何根據以前和未來的價值按行按組改變價值
按組ID,如果X1在給定的時間段爲0,以前的(T-1)和未來(T + 1)的值等於1,填寫X1與1
ID = c("1","1","1","1","1","2","2","2","2","3","3","3")
time = c("1","2","3","4","5","1","2","3","4","1","2","3")
x1 = as.integer(c("0","1","0","1","1","0","0","0","0","1","0","1"))
df = data.frame(ID,time,x1)
數據:
ID time x1
1 1 0
1 2 1
1 3 0
1 4 1
1 5 1
2 1 0
2 2 0
2 3 0
2 4 0
3 1 1
3 2 0
3 3 1
輸出我試圖獲得:
ID time x1
1 1 0
1 2 1
1 3 1
1 4 1
1 5 1
2 1 0
2 2 0
2 3 0
2 4 0
3 1 1
3 2 1
3 3 1