Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert name-value pair to function argument in R

I'm writing an R function, say foo(). I want to be able to pass in the name and value of parameters to evaluate within a function inside foo(). For example:

foo = function(inputArg, inputVal){
  return( rnorm(100, inputArg=inputVal) )
}

Then, I could evaluate

foo("sd", 2)

and get a vector of 100 random normal values with standard deviation equal to 2. How can I do this?

like image 209
random_forest_fanatic Avatar asked Oct 25 '25 10:10

random_forest_fanatic


1 Answers

For this situation, it's best to use the do.call syntax which allows you to pass all the parameters as a list. For example

foo = function(inputArg, inputVal){
  args <- list(100, inputVal)
  names(args) <- c("", inputArg)
  do.call(rnorm, args)
}

and we can call that just as you expect.

foo("sd", 2)

Here args is just a regular list where each element corresponds to a value you would pass as a parameter. You set the names of the list if you want to have named parameters. If you want to leave a parameter as positional (unnamed), set it's name to "".

like image 99
MrFlick Avatar answered Oct 27 '25 22:10

MrFlick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!