Home > front end >  How to apply list directly in for function arguments?
How to apply list directly in for function arguments?

Time:12-11

I'm not exactly sure how to ask this question, so here is an example

ex_func <- function(x, y) {
  return(x^4 - x^2 - y)
}

# and I want to run something like
ex_func(runif(2, 1, 0))

runif(2, 1, 0) returns a vector, with len of 2. I was expecting it to automatically fill the arguments of my function and was wondering what I could do. Obviously, I could save it to some variable and then take the indexes, but I want it to be more automated than that..... This isn't the exact problem I am working on but it suffices as a teaching aide.

CodePudding user response:

The issue is that the result of runif is passed to the x argument of your function, i.e. R will not split a vector into multiple arguments by default. While there are options to do this, a simple fix would be to make your function a function of one argument and use indexing to extract the elements:

ex_func <- function(x) {
  x[1]^4 - x[1]^2 - x[2]
}
set.seed(123)

ex_func(runif(2, 0, 1))
#> [1] -0.8641665

CodePudding user response:

That's what do.call is designed for. The runif has to be provided as.list.

set.seed(42)
do.call(ex_func, as.list(runif(2, 0, 1)))  ## `ex_func` from OP
# [1] -1.073594

CodePudding user response:

Also a tidyverse solution. We use big bang operator !!! to splice a vector into separate values:

library(rlang)

set.seed(123)
exec(ex_func, !!!runif(2, 0, 1))

[1] -0.8641665
  •  Tags:  
  • r
  • Related