Test if an argument of a function is set or not in R
Solution 1
You use the function missing()
for that.
f <- function(p1, p2) {
if(missing(p2)) {
p2=p1^2
}
p1-p2
}
Alternatively, you can set the value of p2 to NULL by default. I sometimes prefer that solution, as it allows for passing arguments to nested functions.
f <- function(p1, p2=NULL) {
if(is.null(p2)) {
p2=p1^2
}
p1-p2
}
f.wrapper <-function(p1,p2=NULL){
p1 <- 2*p1
f(p1,p2)
}
> f.wrapper(1)
[1] -2
> f.wrapper(1,3)
[1] -1
EDIT: you could do this technically with missing()
as well, but then you would have to include a missing()
statement in f.wrapper
as well.
Solution 2
I think '?missing' should do it.
Solution 3
In a case like this you can also use something like this:
f <- function(p1, p2 = p1 ^ 2) {
p1-p2
}
See the part on Lazy evaluation at http://adv-r.had.co.nz/Functions.html
R_User
I really like programming in R, although the documentation is rarly helpful,...
Updated on July 05, 2022Comments
-
R_User almost 2 years
I have a function
f
that takes two parameters (p1
andp2
):If for the parameter
p2
no value was passed to the function, the value ofp1
^2 should be used instead. But how can I find out within the function, if a value is given or not. The problem is that the variablep2
is not initialized if there was no value. Thus I can't test forp2
beingNULL
.f <- function(p1, p2) { if(is.null(p2)) { p2=p1^2 } p1-p2 }
Is it somehow possible to check if a value for
p2
was passed to the function or not? (I could not find anisset()
- function or similar things.) -
Josh O'Brien over 12 years+1 for the
NULL
default alternative. Re: the EDIT you added, how would you passmissing
'ness down through the wrapper function? -
Tommy over 12 years@JoshO'Brien Passing
missing
-ness on is complicated AFAIK - but possible. That's whyNULL
is so much easier in this case. -
Tommy over 12 years... So a separate question might be warranted for passing
missing
-ness on. -
Joris Meys over 12 years@JoshO'Brien That would have to be
if(missing(p2)) f(p1) else f(p1,p2)
. Or you could pass the arguments using the dots argument. -
Josh O'Brien over 12 yearsThanks. FWIW, I can't see how to do this with dots, if both functions have formal args
p1
andp2
. Another alternative uses the following in the body off.wrapper()
:{cl <- match.call(); cl$p1 <- 2*p1; cl[[1]] <- f; eval(cl)}
. All this goes to show just how much cleaner yourNULL
alternative really is! -
Joris Meys over 12 years@JoshO'Brien : you only give
f
the formal argsp1
andp2
.f.wrapper <- function(p1, ...){ blabla f(p1, ...)}
. That would work and is how it's often done in R itself -
Diego over 2 yearsI usually write it like this, so when would
missing
be most appropriate? -
Johan about 2 years@Diego, if you look at the ?missing documentation you'll find an example that would be difficult to implement using this technique.