I'm new on R. I wrote a case when code but I want to parametizer because not always I have n = 5. is it possible?
iris
iris$id_1 = sample(1:10)
iris$id_2 = sample(1:10)
iris$id_3 = sample(1:10)
iris$id_4 = sample(1:10)
iris$id_5 = sample(1:10)
x = 3
iris <-
iris %>%
mutate(
segmento =
case_when(
id_5 >= x ~ 5,
id_4 >= x ~ 4,
id_3 >= x ~ 3,
id_2 >= x ~ 2,
id_1 >= x ~ 1,
)
)
The problem is I have not always 5 "id". Sometimes I have 3 and the code It will be:
iris <-
iris %>%
mutate(
segmento =
case_when(
id_3 >= x ~ 3,
id_2 >= x ~ 2,
id_1 >= x ~ 1,
)
)
Then I need to parametizer it.
Thanks
Instead of using multiple case_when
, based on the description, we can do (if we are comparing the number in the column name, extract that number with sub
, do a comparison and get the column index with max.col
on a logical matrix. Here, we specify last
so that if we have a row with c(FALSE, TRUE, TRUE, TRUE)
, it gives the column index as 4
nm1 <- grep("^id_\\d+", names(df), value = TRUE)
max.col(df[nm1] >= as.numeric(sub("id_", "", nm1))[col(df[nm1])], "last")
Based on the updated post with 'iris' example
nm1 <- grep("^id_\\d+", names(iris), value = TRUE)
max.col(iris[nm1] >= x, "last")