An else
only happens if a previous if
hasn't happened.
When you say
But if b == 1
and a == 0
, Z
will do additional changes to those already done by Y
Then you have two options:
## Option 1: nest Z inside Y
if (a == 1){
X
} else if(a == 0){
Y
if (b == 1){
Z
}
}
## Option 2: just use `if` again (not `else if`):
if (a == 1) {
X
} else if(a == 0) {
Y
}
if (a == 0 & b == 1) {
Z
}
Really, you don't need any else
here at all.
## This will work just as well
## (assuming that `X` can't change the value of a from 1 to 0
if (a == 1) {
X
}
if (a == 0) {
Y
if (b == 1){
Z
}
}
Typically else
is needed when you want to have a "final" action that is done only if none of the previous if
options were used, for example:
# try to guess my number between 1 and 10
if (your_guess == 8) {
print("Congratulations, you guessed my number!")
} else if (your_guess == 7 | your_guess = 9) {
print("Close, but not quite")
} else {
print("Wrong. Not even close!")
}
In the above, else
is useful because I don't want to have enumerate all the other possible guesses (or even bad inputs) that a user might enter. If they guess 8, they win. If they guess 7 or 9, I tell them they were close. Anything else, no matter what it is, I just say "wrong".
Note: this is true for programming languages in general. It is not unique to R.
However, since this is in the R tag, I should mention that R has if{}else{}
and ifelse()
, and they are different.
if{}
(and optionally else{}
) evaluates a single condition, and you can run code to do anything in {}
depending on that condition.
ifelse()
is a vectorized function, it's arguments are test
, yes
, no
. The test
evaluates to a boolean vector of TRUE and FALSE values. The yes
and no
arguments must be vectors of the same length as test
. The result will be a vector of the same length as test
, with the corresponding values of yes
(when test
is TRUE) and no
(when test
is FALSE).