2017-05-26 70 views
0

問題:我想使用dplyrave做到以下幾點:如何根據以前和未來的價值按行按組改變價值

按組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 

回答

3
library(dplyr) 
df %>% 
group_by(id) %>% 
mutate(x1 = ifelse(lead(x1) == 1 & lag(x1) == 1 & x1 == 0, 1, x1)) 

你能夠通過標識和使用邏輯組leadlag功能從dplyr填寫1