0

I understand this title may not make any sense. I searched everywhere but couldn't find an answer. What I'm trying to do is make a function that will take a parameter name for another function, a vector, and then keep calling that function with the parameter value equal to every item in the vector.

For simplicity's sake I'm not dealing with a vector below but just a single integer.

tuner <- function(param, a, ...) {
  myfunction(param = a, ...)
}

and the code would effectively just run

myfunction(param = a)

I can't get this to work! The code actually runs but the resulting call completely ignores the parameter I put in and just runs

myfunction()

instead. Any solutions?

Vroogpd
  • 3
  • 1
  • How exactly are you calling `tuner`? Note that you can't treat parameter names like variables in R. You would need a special syntax for that. Possibly using `do.call` or `:=` with `eval_tidy` from `rlang`. It would be eaiser to help with a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with code and data we can actually run to test and verify possible solutions. – MrFlick Oct 19 '20 at 00:20

1 Answers1

0

You can't really treat parameter names as variables that need to be evaluated in R. Onw work around would be to build a list of parameters and then pass that to do.call. For eample

myfunction <- function(x=1, y=5)  {
  x+y
}

tuner <- function(param, a, ...) {
  do.call("myfunction", c(setNames(list(a), param), list(...)))
}

tuner("x", 100)
# [1] 105
tuner("y", 100)
# [1] 101
tuner("y", 100, 2)
# [1] 102

Another way using rlang would be

library(rlang)
tuner <- function(param, a, ...) {
  args <- exprs(!!param := a, ...)
  eval_tidy(expr(myfunction(!!!args)))
}

which would give the same results.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Wow! Extremely helpful. Thank you so much & additional thanks for guidelines for my next question! – Vroogpd Oct 19 '20 at 01:00