Reputation: 1175
Can I create a function with the default value of an argument set to the value of a variable at the time of creation?
Something like,
a=1
fn = function(arg1 = a) {
print (arg1+1)
}
fn
would show
function(arg1 = 1) {
print (arg1+1)
}
Upvotes: 1
Views: 166
Reputation: 1175
Helped by help for bquote
function. Here is what I found working for me.
It does not look straight forward to me but it works.
a=1
fn <- eval(bquote( function(arg1 = .(a)) {
print (arg1+1)
} ))
fn
fn(3)
eval(bquote())
and .(a)
are the point.
I found the hows but I don't think I fully understood it. So anyone can help me understand how it works, I will be glad to take it as an answer.
Upvotes: 1
Reputation: 76
One way to do this is to use the global options in R:
fn <- function(arg1 = getOption("arg1", 1)) {
print(arg1 + 1)
}
fn() # returns 2
options(arg1 = 5)
fn() # returns 6
fn(2) # returns 3
options(arg1 = NULL)
fn() # returns 2 again
I think the above solution is cleaner compared to using a global variable in .GlobalEnv, but here is also how you can do it with a global variable in .GlobalEnv:
fn2 <- function(arg1 = if( is.null(.GlobalEnv[["a"]]) ) 1 else .GlobalEnv[["a"]]) {
print(arg1+1)
}
fn2() # this returns an empty vector
a <- 5
fn2() # this returns 6
Upvotes: 1