0

This is a very common question: 1, 2, 3, 4, 5, and still I cannot find even an answer to my problem.

If a == 1, then do X.
If a == 0, then do Y.
If a == 0 and b == 1, then do Z.

Just to explain: the if else statements has to do Y if a==0 no matter the value of b. But if b == 1 and a == 0, Z will do additional changes to those already done by Y.

My current code and its error:

if (a == 1){
X
} else if(a == 0){
Y
} else if (a == 0 & b == 1){ 
Z}

Error in !criterion : invalid argument type
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
Chris
  • 2,019
  • 5
  • 22
  • 67

2 Answers2

3

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).
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
2

I believe you want to include Z in the second condition like this:

if (a == 1){X}
else if(a == 0){
    Y
    if (b == 1){Z}
}
python_enthusiast
  • 896
  • 2
  • 7
  • 26