Search notes:

R: if statement

a <- 3
b <- 2

if ( a < b) {

    message (paste(a, "<", b));

} else if ( a == b) {

    message (paste(a, "==", b));

} else {

    message (paste(a, ">=", b));

}
Github repository about-r, path: /statements/if/basic.R

Testing for equality

As in C, two variables are tested for equality with the duplication of the equal sign (==):
var_1 <- 42     ;
var_2 <- 20 + 22;

if (var_1 == var_2) {
  print("They're equal");
}
Github repository about-r, path: /statements/if/equal.R

Testing vectors

Testing for equality with == might cause some problems if the tested variables are vectors whose length is greater than one. The if statement in the following example only compares the first element of either vector. Since they're equal, the if statement evaluates the comparison as true, which might not be what was intended.
a <- c('foo', 'bar', 'baz');
b <- c('foo', 'X'  , 'Y'  );

if (a == b) {
  print("They're equal");
} else {
  print("They're different");
}
Github repository about-r, path: /statements/if/vector.R
A better alternative is to use the identical() function.

else

If an if is combined with an else, the else needs to be on the same line as the closing curly brace of the if part, otherwise, the error unexpected '}' in "}" is thrown.
if (TRUE) {
  print('Hello world');
}
else {
  print('Good bye!');
}
Github repository about-r, path: /statements/if/unexpected.R
The following code snippet runs without error:
if (TRUE) {
  print('Hello world');
} else {
  print('Good bye!');
}
Github repository about-r, path: /statements/if/else.R

Variable scoping

Variables have function scope. So, variables that are »declared« within the if or else body are visible outside the if statement.
f <- function(a) {

  five    <-  5;
  result  <- -1;

  if ( a > five) {
    result <- a * a;
    v      <- 'greater than';
  }
  else {
    result <- result * a;
    v      <- 'less than';
  }

  paste(v, result);
}

f(4); # less than -4
f(6); # greater than 36

# print(cat('five = ', five)) # object five not found
Github repository about-r, path: /statements/if/variable-scope.R

See also

The if statement does not operate on vectors. Functions that contain an if statement might be vectorized when used with vectors.
R statements

Index