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
In your example, round0 isn't missing, it's set to round1
which is undefined (as opposed to missing).
The best way in general of doing this is to use a default value, in your case FALSE
:
foo = function(a, round0 = FALSE) {
a = a * pi
if (!round0) round(a)
else a
}
bar = function(b) {
round1 <- FALSE
if (b > 10) round1=TRUE
foo(b, round1)
}
or where the default value cannot easily be expressed in the parameter list:
foo = function(a, round0 = NULL) {
a = a * pi
if(!is.null(round0)) round(a)
else a
}
bar = function(b) {
round1 <- NULL
if (b > 10) round1=TRUE
foo(b, round1)
}
Note in both cases you need to set the parameter to be the default value manually in your calling function.
You could also call your foo
function with or without an argument if needed within your if
statement:
bar = function(b) {
if (b > 10) foo(b, TRUE) else foo(b)
}
An alternative approach that shows how to generate a missing value is shown by @moody_mudskipper’s answer.