[R] Do NOT use ifelse() if you can use if(.) else . [was "Checking .."]

peter dalgaard pdalgd at gmail.com
Tue Dec 23 12:57:20 CET 2014


> On 23 Dec 2014, at 10:05 , Martin Maechler <maechler at stat.math.ethz.ch> wrote:
> 
> 
> In cases like this one when the condition 'Cond' is a
> simple TRUE or FALSE (i.e. of length 1), using
> 
> 	if(Cond) A else B
> 
> instead of
> 
> 	ifelse(Cond, A, B)
> 
> is
> 
>  1. much more R - like  [[ "everything you do is a function call" ]]
>     hence much more elegant
> 
>  2. considerably more efficient.
> 
>  3. :-) less typing: uses two "," less ;-)
> 

4. Considerably less confusing in terms of the class of the result.

> ifelse (TRUE, Sys.Date(), as.Date("2014-1-1") )
[1] 16427
> ifelse (FALSE, Sys.Date(), as.Date("2014-1-1") )
[1] 16071
> if (TRUE) Sys.Date() else as.Date("2014-1-1") 
[1] "2014-12-23"
> if (FALSE) Sys.Date() else as.Date("2014-1-1") 
[1] "2014-01-01"

(S/R made the Solomonic decision to take the class of the result of ifelse() from the _condition_ part, which is the only possibility common to both cases, but most likely also something that noone would ever actually want.)

 
-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list