On Mon, Jun 8, 2009 at 3:36 PM, Don MacQueen <m...@llnl.gov> wrote:

Though I do agree that the way you've written the general case with any/
is.na and sum/na.rm is cleaner and clearer because more general, I don't
agree at all with what you say about nested ifelse's vs. a series of
assignments:


> In my opinion, nested ifelse() expressions are difficult to read and
> understand, and therefore difficult to get right.
> Easier to write one expression for each of your criteria. But do the last
> one first
>

In the ifelse case, it is easy to trace exactly what happens in each case,
because all the cases are disjoint.  This becomes especially clear if
written with a lot of whitespace and proper indentation:

ifelse( is.na(X1),
     X2,                                      # the is.na(X1) case
     ifelse( is.na(X2),           # the !is.na(X1) case
                    X1,                       # the !is.na(X1) & is.na(X2)
case
                    X1+X2 )))              # the !is.na(X1) & !is.na(X2)
case

I suppose it might be clearer for some users at least if you wrote out *all*
the cases, even though they're not necessary:

ifelse( is.na(X1),
     ifelse( is.na(X2),            # the is.na(X1) cases
                    NA,                      # the is.na(X1) & is.na(X2)
case
                    X2 )))                    # the is.na(X1) & !is.na(X2)
case
     ifelse( is.na(X2),            # the !is.na(X1) cases
                    X1,                       # the !is.na(X1) & is.na(X2)
case
                    X1+X2 )))              # the !is.na(X1) & !is.na(X2)
case

On the other hand, with the multiple assignment case, if you're not careful,
it's easy to have different statements overwriting each other's results in
unintended ways.  For those who've been around programming for a while, they
may recall Dijkstra's "goto considered harmful" letter -- which is echoed by
functional programming's "assignment considered harmful"!

            -s

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
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.

Reply via email to