I have a function in R with a lot of default arguments, that I want to use multiple times. I want to be able to change those without having to write it all the time.
This is easy in Python like this:
def f(x, y, optional1=1, optional2=2, optional3=3):
return (x y optional1 optional2 optional3)
args = (10, 20)
print(f(1,2, *args)) #this prints 36 = 1 2 10 20 3
now I have an R function f = function(x,y, optional1=1, optional2=2, optional3=3)
but I have not found a way of doing something similar to the example above.
I was hoping something could be done with the ellipsis (...) but seems like that's only for a variable amount of arguments in the function definition.
Doing something like
g = function(x,y){
return(f(x,y, 10, 20, 30)
}
would work but I was wondering if there was a cleaner and more readable way of doing this.
Thanks.
CodePudding user response:
There are a few ways, but you can use do.call()
.
f <- function(x, y, optional1 = 1, optional2 = 2, optional3 = 3){
return(x y optional1 optional2 optional3)
}
f(1, 2, 10, 20)
# [1] 36
Using do.call()
this will look like the following.
args <- list(optional1 = 10, optional2 = 20)
do.call(f, c(x = 1, y = 2, args))
# [1] 36
Another way using rlang
saves a bit of typing, but is generally the same thing.
library(rlang)
exec(f, x = 1, y = 2, !!!args)
#[1] 36
If you are doing this a lot, you can take the approach you started and wrap a function.
g <- function(x, y, arg_list) {
do.call(f, c(x = x, y = y, arg_list))
}
g(1, 2, args)
# [1] 36