简体   繁体   中英

setting a function argument default value as a variable value at the time of creation of the function

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)
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM