[R] if documentation

Martin Maechler m@ech|er @end|ng |rom @t@t@m@th@ethz@ch
Wed Dec 7 12:16:03 CET 2022


>>>>> PIKAL Petr 
>>>>>     on Wed, 7 Dec 2022 07:04:38 +0000 writes:

    > Hallo all Not sure if it is appropriate place but as I am
    > not involved in r-devel list I post here.

 

    > Documentation for Control (if, for, while, .) is missing
    > "if else" command.  Although it can be find online
    > elsewhere I believe that adding it either as an example or
    > as a third entry and paragraph about nested if's could be
    > beneficial.

 

    > if(cond) cons.expr else if (cond) alt.expr else alt2.expr

    > Nested if expressions are better realized with "else if"
    > instead of sequence of plain "else" control statements
    > especially when using several of them.

I agree.  However there is no "else if" special.

As everything that *happens* in R is a function call (John Chambers),
indeed, `if` is a function too, with an unusual syntax which may
involve `else`.

If you look more closely, `if` is a function with 3 arguments,
where the last (3rd) is optional and has a default of NULL :

Some code towards proving the above :


(t1 <- if(TRUE)  1:3 )         # is identical to  if(TRUE) 1:3 else NULL
f1  <- if(FALSE) 1:3           # is identical to
f2  <- if(FALSE) 1:3 else NULL
identical(f1,f2)
f3  <- if(FALSE) 1:3 else 111

`if`(TRUE, 1:3)
`if`(TRUE, 1:3, NULL)

`if`(FALSE, 1:3)   # returns invisibly
`if`(FALSE, 1:3, NULL)
`if`(FALSE, 1:3, 111)

--------------

So, 'if(.) else'  or 'if(...) else if(..) ..'
etc are
all just versions of calling the `if` function sometimes, in a
nested way.



More information about the R-help mailing list