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");
}
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.
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