[R] match.arg: how to prevent users from not specifying a value

William Dunlap wdunlap at tibco.com
Wed Aug 19 18:19:00 CEST 2015


If you want to force the user to enter the 'type' argument,
move the vector of choices out of the argument list
and into the call to match.arg():

   f1 <- function(type, ...) {
       match.arg(type, c("A", "B", "C"))
   }
   f1()
   #Error in match.arg(type, c("A", "B", "C")) :
   #  argument "type" is missing, with no default
   f1("X")
   #Error in match.arg(type, c("A", "B", "C")) :
   #  'arg' should be one of “A”, “B”, “C”
   f1("B")
   #[1] "B"


Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Tue, Aug 18, 2015 at 5:42 PM, Youyi Fong <yfong at fhcrc.org> wrote:

> Hello, I have a function that looks like
>
> f=function( type=c("dummy,"A","B,"C"), ... ) {
>     type<-match.arg(type)
>     if (type=="dummy") stop("Please choose a type that is not dummy.")
>     ...
> }
>
> I put a "dummy" in the list of choices as a mechanism to prevent users
> from not specifying a value for "type" when calling the function. My
> question is whether there is a better way to achieve it that does not
> need "dummy".
>
> Thanks,
> Youyi
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list