# [R] take precisely one named argument

Liaw, Andy andy_liaw at merck.com
Fri Dec 17 14:16:04 CET 2004

```Here's my attempt:

> f <- function(...) {
+     argList <- list(...)
+     if (length(argList) != 1) stop("Wrong number of arguments!")
+     if (length(names(argList)) != 1 || ! names(argList) %in% c("a", "b"))
+         stop("Wrong name for argument!")
+     x <- argList[[1]] * if (names(argList) == "a") 1 else 2
+     x
+ }
> f(a=6)
Error in f(6) : Wrong name for argument!
> f(b=6)
[1] 6
> f(c=6)
[1] 12
> f(c=6)
Error in f(c = 6) : Wrong name for argument!

HTH,
Andy

> From: Robin Hankin
>
> 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