We frequently use conditional statements to make decisions.

For example, if a student’s test score is greater than or equal to 50%, he/she will pass the course. Otherwise, the student will fail the course.

We will write this in R to be:

score <- 70

if (score >= 50){
  print("Pass")
}else{
  print("Fail")
}
## [1] "Pass"

The basic structure of the if statement in R is:

if (conditional_statement){
  # Write something that you would like to do if the code is correct
}else{
  # Write something that you would like to do if the code is incorrect
}

Operations that are frequently used in if statements:

Condition Example Meaning
> a > b Check if a is greater than b
>= a >= b Check if a is greater than or equal to b
< a < b Check if a is less than b
<= a <= b Check if a is less than or equal to b
== a == b Check if a is equal to b

We can also write if statement with multiple conditions:

if (condition1) { 
      # Condition1 is correct
    } else if (condition2) {
      # Condition2 is correct
    } else if  (condition3) {
      # Condition3 is correct
    } else {
      # All conditions are incorrect
}

Example: Letter Grade

suppose that we would like to assign letter grades to the student based on the following condition:

score <- 80

if (score >= 90){
  print("A")
} else if (score >= 70){
  print("B")
} else if (score >= 50){
  print("C")
} else {
  print("Fail")
}
## [1] "B"

And/Or

There is a concept of “and” and “or” in conditional statement. For example, we might be interested in:

  1. Person whose math score is above 70 and English score is above 70

  2. Person whose math score is above 70 or English score is above 70

In R:

Let’s illustrate these examples:

Example 1:

Get a person whose math score is above 70 and English score is above 70

math <- 50
english <- 80

if (math > 70 && english > 70){
  print('True')
} else {
  print('False')
}
## [1] "False"

Example 2:

Get a person whose math score is above 70 or English score is above 70

math <- 50
english <- 80

if (math > 70 || english > 70){
  print('True')
} else {
  print('False')
}
## [1] "True"

Even though the values for both variables are the same, we get a different output depending on “and”/“or” statement.

©2021 by Daiki Tagami. All rights reserved.