我有一个看起来像这样的数据框:
id <- c(1, 1, 1, 2, 2, 2, 3, 3, 3)
x <- c(1, 1, 0, 0, 1, 1, 1, 1, 1)
df <- data.frame(id, x)
我只想为每个 id 保留 = 1 的第一个值,否则我希望它 = 0,如下所示:
id x
<dbl> <dbl>
1 1 1
2 1 0
3 1 0
4 2 0
5 2 1
6 2 0
7 3 1
8 3 0
9 3 0
我试过这段代码,但没有运气:
df %>%
group_by(id) %>%
mutate(x = if (any(x == 1)) replace(x,
row_number() != 1, 0) else x)
```
最佳答案
使用 replace
你可以做 :
library(dplyr)
df %>% group_by(id) %>% mutate(y = replace(x, -match(1L, x), 0L))
#OR
#mutate(y = replace(x, which.max(x), 0L))
# id x y
# <dbl> <dbl> <dbl>
#1 1 1 1
#2 1 1 0
#3 1 0 0
#4 2 0 0
#5 2 1 1
#6 2 1 0
#7 3 1 1
#8 3 1 0
#9 3 1 0
关于根据 r 中的行号替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61495092/