这可能很简单,但我错过了。在示例中,我有几个 id,每个 id 都有多个值。在每个
id
中,我希望仅在出现 x
后才能将 0
设置为等于 2
,而其他值保持不变。
有没有
dplyr
的方法可以做到这一点?
test <- structure(list(id = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3,
3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8,
8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10), x = c(0L, 1L, 1L,
2L, 1L, 0L, 0L, 1L, 2L, 1L, 0L, 0L, 1L, 2L, 1L, 0L, 0L, 0L, 0L,
1L, 1L, 2L, 1L, 0L, 0L, 2L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 2L,
1L, 0L, 0L, 2L, 1L, 1L, 0L, 1L, 2L, 1L, 1L)), row.names = c(NA,
-46L), class = "data.frame")
> head(test, 10)
id x
1 1 0
2 1 1
3 1 1
4 1 2
5 1 1
6 2 0
7 2 0
8 2 1
9 2 2
10 2 1
如果我理解正确,这就是你想要的输出
library(dplyr)
head(test,10) %>%
mutate(result = if_else(c(x[1],na.omit(lag(x))) == 2,0,x))
id x result
1 1 0 0
2 1 1 1
3 1 1 1
4 1 2 2
5 1 1 0
6 2 0 0
7 2 0 0
8 2 1 1
9 2 2 2
10 2 1 0