[R] "if" within a function

Martin Maechler maechler at stat.math.ethz.ch
Thu Jun 21 14:19:41 CEST 2007


>>>>> "HO" == Hong Ooi <Hong.Ooi at iag.com.au>
>>>>>     on Thu, 21 Jun 2007 15:49:42 +1000 writes:

    HO> R doesn't use the 'functionname = result' idiom to return a value from a
    HO> function. It looks like you're after:

    HO> aaa <- function(a)
    HO> {
    HO>   if(a == 1) return(1)
    HO>   if(a != 1) return(2)
    HO> }


    HO> or


    HO> aaa <- function(a)
    HO> {
    HO>   if(a == 1) 1
    HO>   else 2
    HO> }

    HO> see ?return

or to continue the "Variations on a theme" :

   aaa <- function(a)  if(a == 1) 1 else 2

(You don't need "{" .. "}" :
   some people argue you should
   always use them for defensive programming 
   where I would not use them in simple "one liners",
   but would use them otherwise
)

Martin Maechler, ETH Zurich



More information about the R-help mailing list