📜 Evaluating List as Function Arguments in R

October 23, 2019  

library(rlang)

list_of_arguments = list(
  par1 = "Choc",
  par2 = "Top",
  par3 = "Icecream",
  repnum = 5
)

fun_with_funcs <- function(par1, par2, par3, repnum) {
  rep(paste(par1, par2, par3, sep = "_"), repnum)
}
# Base R Solution, issues with env I assume?
do.call("fun_with_funcs", list_of_arguments)

## [1] "Choc_Top_Icecream" "Choc_Top_Icecream" "Choc_Top_Icecream"
## [4] "Choc_Top_Icecream" "Choc_Top_Icecream"
# The rlang exec method not requiring multiple steps
# The combination of quotation and unquotation is called quasiquotation
rlang::exec("fun_with_funcs", !!!list_of_arguments)

## [1] "Choc_Top_Icecream" "Choc_Top_Icecream" "Choc_Top_Icecream"
## [4] "Choc_Top_Icecream" "Choc_Top_Icecream"
# Finer controlled version from rlang
eval(rlang::expr(fun_with_funcs(!!!list_of_arguments)))

## [1] "Choc_Top_Icecream" "Choc_Top_Icecream" "Choc_Top_Icecream"
## [4] "Choc_Top_Icecream" "Choc_Top_Icecream"
# With eval_tidy, I think I get why this works...
eval_tidy(quo(fun_with_funcs(!!!list_of_arguments)))

## [1] "Choc_Top_Icecream" "Choc_Top_Icecream" "Choc_Top_Icecream"
## [4] "Choc_Top_Icecream" "Choc_Top_Icecream"
# You'd probably never do this, but then getting the list as the expression
expr(c(!!!list_of_arguments))