I am using the dplyr::coalesce
and dplyr::mutate
to find all first non-missing values and stuff that into a new variable. However, I would like to also create a new variable with the information on which variable is used to infill the new variable.
Here is an example:
df <- dataframe(
St1 = c(1, NA, NA, NA),
St2 = c(NA, 3, NA, NA),
St3 = c(NA, NA, 12, NA),
St4 = c(NA, NA, NA, 4))
What I do :
df <- df %>%
mutate(df.coalesce = coalesce(St1, St2, St3, St4)) %>%
select(df.coalesce)
Result:
df.coalesce
1
3
12
4
Desired result:
Station df.coalesce
St.1 1
St.2 3
St.3 12
St.4 4
Is there a way to do that using the tidyverse grammar?
Thanks!