I need to obtain values of a list of grades (math, language, sci, etc.) conditional on the presence of valid values in 2016 (validity_2016=="yes"), into a new variable called grades_{subjects} (eg. grades_math).
df<-tibble(person = c("Alice", "Bob", "Mary"),
validity_2016 = c(NA, "yes", NA),
likes_ham = c("no", "yes", "yes"),
grades_math_2015=c(6,2,4),
grades_math_2016=c(3,5,7),
grades_language_2015=c(7,1,9),
grades_language_2016=c(3,6,7),
grades_sci_2015=c(7,1,9),
grades_sci_2016=c(3,6,7))
I was wondering the viability to use dplyr's mutate_at or mutate(across, in the following way:
dplyr::mutate(across(grades_math_2016, grades_language_2016,grades_sci_2016),
~dplyr::case_when(!is.na(validity_2016)~list(grades_math_2015,grades_language_2015,grades_sci_2015)~.),
.names="{col}"))
The outcomes should look like this:
df<-tibble(person = c("Alice", "Bob", "Mary"),
validity_2016 = c(NA, "yes", NA),
likes_ham = c("no", "yes", "yes"),
grades_math_2015=c(6,2,4),
grades_math_2016=c(3,5,7),
grades_language_2015=c(7,1,9),
grades_language_2016=c(3,6,7),
grades_sci_2015=c(7,1,9),
grades_sci_2016=c(3,6,7),
grades_math=c(6,5,4),
grades_language=c(7,6,7),
grades_sci=c(7,6,9))