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?
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 "".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With