ASGR
ASGR

Reputation: 86

Inherit R function argument from global variable

I am trying to create a function where the default argument is given by a variable that only exists in the environment temporarily, e.g.:

arg=1:10
test=function(x=arg[3]){2*x}

> test()
[1] 6

The above works fine, as long as arg exists in the function environment. However, if I remove arg:

> rm(arg)
> test()
> Error in test() : object 'arg' not found

Is there a way such that the default argument is taken as 3, even when arg ceases to exist? I have a feeling the correct answer involves some mixture of eval, quote and/or substitute, but I can't seem to find the correct incantation.

Upvotes: 0

Views: 375

Answers (2)

ASGR
ASGR

Reputation: 86

The post above got me on the right track. Using formals:

arg=1:10
test=function(x){x*2}
formals(test)$x=eval(arg[3])
rm(arg)
test()

[1] 6

And that is what I was looking to achieve.

Upvotes: 1

Tensibai
Tensibai

Reputation: 15784

The proper way to do it in my opinion would be:

test <- function(x=3) { 2 *x }

and then call it with an argument:

arg<-1:10
test(arg[3])

This way the default value is 3, then you pass it the argument you wish at runtime, if you call it without argument test() it will use the default.

Upvotes: 1

Related Questions