1

In C++ the ternary operator enables shorthand conditional assignment of variable values:

x = y > 2 ? y : 2; 

In R, the closest operation of which I am aware is the following:

ifelse(y > 2, x <- y, x <- 2)

It just feels clumsy and looks OO awkward to type x twice on the same line, especially when doing this dozens of times. Is there a cleaner method for conditional assignment in R?

zdebruine
  • 3,687
  • 6
  • 31
  • 50

1 Answers1

5

The closest (in fact, exact) equvalent would be:

x = if (y > 2) y else 2

Or, if you want to perform a vectorised test and assignment:

x = ifelse(y > 2, y, 2)

(For y = 1 : 5, this yields 2 2 3 4 5.)

The important point is that, unlike in C++, (almost) every statement R is an expression with a value. C++ needs the conditional operator because if isn’t an expression. But in R it is, and the value of an if (‹condition›) ‹true› [else ‹false›] expression is the value of either the ‹true› or the ‹false› sub-expression, depending on whether its ‹condition› evaluates to TRUE (and if the false branch is missing, its value is NULL).

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214