The following is the data frame that I have created:
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)
From that data frame, I just only wanted to keep only the first value that is equal to 1 for each id, otherwise, I want it to be 0. My desired output should look like this:
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
I have tried this code, but I am not getting the output:
df %>%
group_by(id) %>%
mutate(x = if (any(x == 1)) replace(x,
row_number() != 1, 0) else x)