I have a number of variables that I want to coalesce together in R. I have extracted them into a vector to use them in the coalesce function. Typing each one of them in the function is a bit tedious. Is there a way to go about it?
library(dplyr)
set.seed(123)
df <- data.frame(
var1 = sample(c(NA, 1, 3), 10, replace = T),
var2 = sample(c(NA, 1, 3), 10, replace = T),
var3 = sample(c(NA, 1, 3), 10, replace = T),
var4 = sample(c(NA, 1, 3), 10, replace = T),
age = floor(rnorm(10, 15, 2)),
gender = factor(round(runif(10, 1, 2)),
labels = c("Male", "Female"))
)
# Desired variables
myvars <- df %>% select(contains("var")) %>% names()
df_new <- df %>%
mutate(finalvar = coalesce(myvars))