[R] take precisely one named argument
(Ted Harding)
Ted.Harding at nessie.mcc.ac.uk
Fri Dec 17 13:56:37 CET 2004
On 17-Dec-04 Robin Hankin wrote:
> Hi
> I want a function that takes precisely one named argument and no
> unnamed arguments. The named argument must be one of "a" or "b".
>
> If "a" is supplied, return "a". If "b" is supplied, return 2*b.
> That is, the desired behaviour is:
>
> R> f(a=4) #return 4
> R> f(b=33) #return 66
> R> f(5) #error
> R> f(a=3,b=5) #error
> R> f(a=3,q=3) #error
> R> f(q=3) #error
>
> The following function is intended to implement this:
>
f <- function(a=NULL, b=NULL){
if(!xor(is.null(a), is.null(b))){
stop("specify exactly one of a and b")
}
if(is.null(a)){return(2*b)}else{return(a)}
}
>
>
> It almost works, but f(6) returns 6 (and should be an error).
>
> What is the best way to accomplish my desired behaviour?
I don't know the *best* way (expert R anatomists will know ... )
but the following dirty handed modification seems to do what
you want:
f <- function(z=NULL, a=NULL, b=NULL){
if(!is.null(z)){
stop("usage: f(a=...) or f(b=...)")
}
if(!xor(is.null(a), is.null(b))){
stop("specify exactly one of a and b")
}
if(is.null(a)){return(2*b)}else{return(a)}
}
(This traps attempts to use f() with an un-named argument).
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861 [NB: New number!]
Date: 17-Dec-04 Time: 12:56:37
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list