R If ... Else


Conditions and If Statements

R supports common logic scenarios from statistics:

Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

These situations can be used in a number of ways, usually "if statements" and loops.

The "if statement" statement is written with a keyword if, and is used to specify a code block to be used when the state says TRUE:

Example
a <- 33
b <- 200

if (b > a) {
  print("b is greater than a")
}

In this example we use two variables, a and b, which are used as part of the statement when assessing whether b is greater than a. Since a is 33, and b is 200, we know that 200 is greater than 33, so we print to check that "b is greater than a".


R uses the curved brackets {} to define the width of the code.



Else If

The else if the keyword is an R-type "if previous conditions were not true, try this condition":

Example
a <- 33
b <- 33

if (b > a) {
  print("b is greater than a")
} else if (a == b) {
  print ("a and b are equal")
}

In this example a is equal to b, so the first condition is not true, but another else if the condition is true, so we print to check that "a and b are equal".

You can use many more else if statements the way you want in R.


If Else

Else keyword captures anything that is not covered by the previous terms:

Example
a <- 200
b <- 33

if (b > a) {
  print("b is greater than a")
} else if (a == b) {
  print("a and b are equal")
} else {
  print("a is greater than b")
}

In this example, a is greater than b, so the original condition is not true, also the else if the condition is not true, then we go to else condition and print it to check that "a is greater than b".

You can also use else without else if:

Example
a <- 200
b <- 33

if (b > a) {
  print("b is greater than a")
} else {
  print("b is not greater than a")
}


Nested If Statements

You can also have if the statements within if statements, this is called nested if statements.

Example
x <- 41

if (x > 10) {
  print("Above ten")
  if (x > 20) {
    print("and also above 20!")
  } else {
    print("but not above 20.")
  }
} else {
  print("below 10.")
}


AND

Symbol & symbol (once) is a sensible operator, and is used to compile conditional statements:

Example

Test if a is greater than b, AND if c is greater than a:

a <- 200
b <- 33
c <- 500

if (a > b & c > a){
  print("Both conditions are true")
}


OR

I | the mark (or) is a sensible operator, and is used to compile conditional statements:

Example

Test if a is greater than b, or if c is greater than a:

a <- 200
b <- 33
c <- 500

if (a > b | a > c){
  print("At least one of the conditions is true")
}