[R] take precisely one named argument
BXC (Bendix Carstensen)
bxc at steno.dk
Fri Dec 17 13:46:18 CET 2004
specify:
f <- function(...,a=NULL,b=NULL) {...etc
Bendix
----------------------
Bendix Carstensen
Senior Statistician
Steno Diabetes Center
Niels Steensens Vej 2
DK-2820 Gentofte
Denmark
tel: +45 44 43 87 38
mob: +45 30 75 87 38
fax: +45 44 43 07 06
bxc at steno.dk
www.biostat.ku.dk/~bxc
----------------------
> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Robin Hankin
> Sent: Friday, December 17, 2004 1:18 PM
> To: R-help at stat.math.ethz.ch
> Subject: [R] take precisely one named argument
>
>
> 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?
>
> --
> Robin Hankin
> Uncertainty Analyst
> Southampton Oceanography Centre
> European Way, Southampton SO14 3ZH, UK
> tel 023-8059-7743
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read
> the posting guide! http://www.R-project.org/posting-guide.html
>
More information about the R-help
mailing list