I have a dataset with names from some variables corresponding to each month (e.g. var1_M1, var1_M2 var2_M1 ...) and I need to summarize by each month (after conditional) and identify the first case when I find a value > 90 and finally indicate the corresponding month.
library(dplyr)
ID <- c("Dave", "Joe", "Steve")
var1_M1 <- c(10, 10, 90)
var1_M2 <- c(30, 90, 95)
var1_M3 <- c(90, 100, 95)
var2_M1 <- c(10, 90, 20)
var2_M2 <- c(33, 10, 100)
var2_M3 <- c(90, 10, 50)
data <- tibble(ID, var1_M1, var1_M2, var1_M3, var2_M1, var2_M2, var2_M3)
# A tibble: 3 x 7
ID var1_M1 var1_M2 var1_M3 var2_M1 var2_M2 var2_M3
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Dave 10 30 90 10 33 90
2 Joe 10 90 100 90 10 10
3 Steve 90 95 95 20 100 50
data %>%
mutate_at(vars(matches(c("M1","M2","M3"))),
list(~ ifelse(. > 90, .,0))) #%>%
#mutate() using map_dfc and if_any ??
Expected output
# A tibble: 3 x 5
ID M1 M2 M3 output
<chr> <dbl> <dbl> <dbl> <dbl>
1 Dave 0 0 0 0
2 Joe 0 0 100 3
3 Steve 0 195 95 2