[R] How to set an argument such that a function treats it as missing?

Duncan Murdoch murdoch.duncan at gmail.com
Sat Nov 13 12:41:47 CET 2010

Marius Hofert wrote:
> Dear expeRts,
> I would like to call a function f from a function g with or without an argument. 
> I use missing() to check if the argument is given. If it is not given, can I set 
> it to anything such that the following function call (to f) behaves as if the argument
> isn't given? It's probably best described by a minimal example (see below).
> The reason why I want to do this is, that I do not have to distinguish between the
> cases when the argument is given or not. By setting it to something (what?) in the
> latter case, I can use the same code in the subsequent part of the function.
> Cheers,
> Marius
> f <- function(x) if(missing(x)) print("f: missing x") else print(x)
> g <- function(x){
> 	if(missing(x)){
> 		print("g: missing x")
> 		x <- NULL # I try to set it to something here such that...

Just leave out the line above, and you'll get both messages printed:

 > g()
[1] "g: missing x"
[1] "f: missing x"

Duncan Murdoch

> 	}
> 	f(x) # ... this call to f behaves like f() 
> } 
> g() # should print "f: missing x" (is this possible?)
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list