0

Is there an equivalent building block in R for

if ($a > $b) {
    echo "a is bigger than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is smaller than b";
}

from PHP or Java?

Klaus
  • 1,946
  • 3
  • 19
  • 34
  • Maybe [this][1] "switch" can help you? [1]: http://stackoverflow.com/questions/10393508/how-to-use-the-switch-statement-in-r-functions – LostAvatar Sep 02 '13 at 08:10
  • For the people who know R but not PHP or Java perhaps describe what `echo` does. Maybe also add the result you want to your post. Maybe also add the PHP and Java tags to your post. – Mark Miller Sep 02 '13 at 08:30
  • `else if` is what you want. – Peter Dutton Sep 02 '13 at 08:30

1 Answers1

3

It's not idiomatic but the answer is yes:

if (a > b) {
  cat("a is bigger than b")
} else if (a == b) {
  cat("a is equal to b")
} else {
  cat("a is smaller than b")
}
flodel
  • 87,577
  • 21
  • 185
  • 223
  • Maybe worth explaining that this is not idiomatic because it is not vectorised. The `ifelse` function is a vectorised alternative. Also, I'd be tempted by `message` rather than `cat` (which is low level and not really meant to be called directly). – Richie Cotton Sep 02 '13 at 12:03
  • Also worth explaining that the curly braces (my edit) are necessary to avoid the possibility that R reads the first two lines as a complete statement then throw `Error: unexpected ’else’ in "else"`. – flodel Sep 02 '13 at 12:08
  • @Richie ```message``` is probably to be recommended but I suppose ```cat``` is arguably closer to ```echo```. – user2739139 Sep 03 '13 at 00:42
  • @flodel That is a good correction. The other option is to put the ```else``` before the line break. Although all work (including the original) if it is defined within a function. – user2739139 Sep 03 '13 at 00:44