I’ve learned that it’s common practice to use optional arguments in function and check them with missing() (e.g. as discussed in SO 22024082)
In this example round0 is the optional argument (I know, round0 could be defined as logical).
foo = function(a, round0) {
a = a * pi
if(!missing(round0)) round(a)
else a
}
But what if I call this function from another function, how can I pass “missing”?
bar = function(b) {
if(b > 10) round1=T
foo(b, round1)
}
If b < 10 then round1 in bar() is not defined, but is passed to foo anyway. If I modify foo():
foo = function(a, round0) {
a = a * pi
print(missing(round0))
print(round0)
if(!missing(round0)) round(a)
else a
}
and run bar(9) the output is:
bar(9)
[1] FALSE
Error in print(round0) : object 'round1' not found
Called from: print(round0)
That means: round0 is not missing, but can’t be accessed either?
I don’t want to use different function calls in bar(), if there are several optional arguments in foo(), I would have to write a function call for every missing/not missing - combination of all optional arguments.
Is it possible to pass "missing", or what other solution would apply for this problem?
round1=F
at start ofbar
and updatefoo
withif(!missing(round0) && round0)
. Missing allow you to callfoo(a)
orfoo(a,T/F)
, if you call it with two parameters, the second parameter is not missing and have to be resolvable. – Pastelkimissing
returnsFALSE
as soon as the promise object that represents the function argument has a non-empty expression slot. Add the lineprint(substitute(round0))
right aftera = a * pi
in your modifiedfoo
function and then executefoo(9)
.substitute
will extract the expression slot. It will print nothing, i.e., an empty expression slot forround0
. Now trybar(9)
. This printsround1
. But when you useprint
, R will try to evaluateround1
which was not defined yet (lazy evaluation). – Lowpitched