如何按组逐行更改基于先前和未来值的值

时间:2017-05-26 16:08:09

标签: r dplyr

问题:我正在尝试使用dplyrave执行以下操作:

按组ID,如果给定时间段的x1为0且前一个(t-1)和未来(t + 1)值等于1,则用1​​填充x1。

     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  

1 个答案:

答案 0 :(得分:3)

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

您可以按ID分组,并使用来自lead的{​​{1}}和lag函数的逻辑来填写1。