1

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)
}
2
  • I would use bquote or substitute and then eval the expression. Commented Nov 22, 2018 at 9:53
  • Thank you for the clue. Could you elaborate on how it works... I figured out how to do it but I am not sure I fully understand how it works... Commented Nov 22, 2018 at 10:53

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. It could be a way around.
1

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.

1 Comment

It's basic computing on the language. You construct an expression and then evaluate it. This ensures that the default function parameter is a value and not a symbol.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.