Mathematica's Which function is a generalized If:
Which[test_1, value_1, test_2, value_2, …]evaluates each of the
test_iin turn, returning the value of thevalue_icorresponding to the first one that yieldsTrue.
It's nothing more than a handy way to get rid of superfluous syntax from long sequences of nested simple if-else tests.
Does R have an equivalent function?
BTW, I know that I can always do something like
if (test_1) value_1 else if (test_2) value_2 else ... value_n else default
or, equivalently,
if (test_1) value_1 else
if (test_2) value_2 else
...
if (test_n) value_n else
default
...but, as I already alluded to, when compared to Which, nested if-else statements bring in a lot of superfluous syntax.
Also, I'm aware of
ifelse(t_1, v_1, ifelse(t_2, v_2, ..., ifelse(t_n, v_n, default)...))
...but the results are sensitive to the shape of the tests, so it is not strictly equivalent to nested if-else statements.
Lastly, R's switch statement is similar to what I'm looking for, in that it encapsulates a dispatch over a sequence of tests, but it's not quite the same thing. In
switch(expr,
case_1 = value_1,
case_2 = value_2,
...
case_n = value_n,
default)
...the tests are all equality comparisons of expr against the case_i, whereas in Which, etc., the tests are arbitrary boolean expressions.