Message-ID: <A6BB278845329C41A08CB3C52A0E2C1002256EF7@ut40se02.atk.com>
Date: 2010-01-19T22:21:31Z
From: Lyman, Mark
Subject: coping with a warning in if()
In-Reply-To: <mailman.21.1263898808.19274.r-help@r-project.org>
H?ctor Villalobos <hvillalo <at> ipn.mx> writes:
>
> Hi,
>
> I'm sure this one is very easy....
>
> I am trying to write a function where one of its arguments has two posible (strings) values,
> defaulting to one of them if none is specified. My problem is that when evaluating the function
> the following warning is produced:
>
> "the condition has length > 1 and only the first element will be used"
>
> I've read the help page of if() but I don't get it because when evaluating step by step the
> warning is not produced.
>
> Omitting the details of my function, below is an example of this
>
> ## Function
> fun <- function( n, result = c("simple", "complete") )
> {
> if ( is.null(result) )
> result <- "simple"
> if ( !(result %in% c("simple", "s", "complete", "c")) ) {
> stop("specify type of result 'simple' or 'complete'")
> } else {
> res <- rnorm(n)
> res
> }
> }
Take a look at ?match.arg for one solution.
fun <- function( n, result = c("simple", "complete") )
{
result <- match.arg(result)
res <- rnorm(n)
res
}
fun(n=20)
fun(n=20, result="simple")
fun(n=20, result="comp")
fun(n=20, result="something")
Mark Lyman