Skip to content

Argument validation within functions

5 messages · R. Michael Weylandt, Johannes Radinger, Berwin A Turlach +2 more

#
Use the ! (not) operator.

Not sure what you mean by " as the stop() stops the total function":
try the following

f <- function(a){
? ?stopifnot(a > 3)
? ?return(a^2)
}

f(2)
f(4)

Michael

(PS -- It's usually asked to cc the list so that this all gets
threaded properly in folks' mailboxes)
On Tue, Dec 6, 2011 at 7:46 AM, Johannes Radinger <JRadinger at gmx.at> wrote:
#
Thank you, i didn't know that the !operator is
also working for is.numeric etc.

Anyway I want to test if an argument is set in the
function call and if not a code is executed... So 
far I tried:

f <-function(a,b){
	if(!exists("b")) print("exists: b is not set")
	if(is.null("b")) print("is.null : b is not set")
}

f(a=1,b=2)
f(a=1)
f(b=2)

I don't really know how to do it...e.g: for f(a=1) b is not set
so it also can't be NULL (thats why is.null is not working). I
just want to "test" if it is set with the function call not outside
the function or before etc.

/Johannes

-------- Original-Nachricht --------
--
#
G'day Johannes,

On Tue, 06 Dec 2011 16:15:21 +0100
"Johannes Radinger" <JRadinger at gmx.at> wrote:

            
?missing

Cheers,
	
	Berwin

========================== Full address ============================
A/Prof Berwin A Turlach               Tel.: +61 (8) 6488 3338 (secr)
School of Maths and Stats (M019)            +61 (8) 6488 3383 (self)
The University of Western Australia   FAX : +61 (8) 6488 1028
35 Stirling Highway                   
Crawley WA 6009                e-mail: Berwin.Turlach at gmail.com
Australia                        http://www.maths.uwa.edu.au/~berwin
#
you may be looking for ?missing

f <- function(a,b) {
     if (missing(b)) print("b is missing")
}

f(a=1, b=2)
f(a=1)
f(b=2)

Regards,
Enrico

Am 06.12.2011 16:15, schrieb Johannes Radinger:

  
    
#
On Tue, Dec 6, 2011 at 7:15 AM, Johannes Radinger <JRadinger at gmx.at> wrote:
Read (more carefully?) R docs, please. ! is a unary function that
takes a logical argument(and will coerce to logical nonlogical
arguments if it can); is.numeric() returns a logical, so of course it
should "work". Ergo your failure to understand indicates a fundamental
hole in your understanding of how R works.

-- Bert