I want to save the position of the first TRUE
in level
variable within each id
. I am doing the below:
library(tidyverse)
data <- data %>%
group_by(id) %>%
mutate(first_true = min(which(data$level == TRUE))) %>%
ungroup()
However, the result for first_true
is the same for all id
. group_by(id)
is not working. Any idea of what might be happening?
Example data:
id <- c(1,1,1,2,2,2,3,3,3)
level <- c(FALSE,FALSE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE,TRUE)
data <- data.frame(id, level)
data$level <- as.logical(data$level)
I would like to obtain:
id level
1 0
1 0
1 0
2 2
2 2
2 2
3 1
3 1
3 1
You can try
data %>%
mutate(first_true = ifelse(any(level), min(which(level)), 0), .by = id)
which gives
id level first_true
1 1 FALSE 0
2 1 FALSE 0
3 1 FALSE 0
4 2 FALSE 2
5 2 TRUE 2
6 2 TRUE 2
7 3 TRUE 1
8 3 TRUE 1
9 3 TRUE 1