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)) 2 Answers
Evaluate with !!! and unpack with rlang::syms:
df %>% mutate(finalvar = coalesce(!!! rlang::syms(myvars))) Or directly attaching rlang:
library(rlang) df %>% mutate(finalvar = coalesce(!!! syms(myvars))) Both Output:
var1 var2 var3 var4 age gender finalvar 1 3 1 NA NA 14 Female 3 2 3 1 NA 3 17 Female 3 3 3 NA 3 3 14 Male 3 4 1 1 1 NA 12 Female 1 5 3 3 3 3 13 Female 3 6 1 NA 1 1 16 Female 1 7 1 3 NA NA 14 Male 1 8 1 3 1 3 12 Male 1 9 3 NA 3 NA 13 Male 3 10 NA NA 1 NA 14 Male 1 Using invoke
library(dplyr) library(purrr) df %>% mutate(finalvar = invoke(coalesce, across(all_of(myvars)))) var1 var2 var3 var4 age gender finalvar 1 3 1 NA NA 14 Female 3 2 3 1 NA 3 17 Female 3 3 3 NA 3 3 14 Male 3 4 1 1 1 NA 12 Female 1 5 3 3 3 3 13 Female 3 6 1 NA 1 1 16 Female 1 7 1 3 NA NA 14 Male 1 8 1 3 1 3 12 Male 1 9 3 NA 3 NA 13 Male 3 10 NA NA 1 NA 14 Male 1 4