3.2 Conditional

Perform a different set of statement(s) based on whether the condition is true or false.

3.2.1 Simple if statement

A block of code will only be executed only if the condition is true.

if (condition){
  blocks to execute when condition hold
} 

Note that the condition must be either TRUE or FALSE. If it is NA, then the code cannot be executed.

Here is our first example of simple-if statement:

x <- 1
y <- 2
if(x < y){
  print("Yes!")
}
## [1] "Yes!"

In this example, the statement will executed since the condition holds.

Alternatively, let us see our second example:

x <- 1
y <- 2
if(x > y){
  print("Yes!")
}

In this example, the statement will be executed since the condition does not hold.

3.2.2 if-else statement

A block of code will only be executed only if the condition is true but another block will be exectued otherwise.

if (condition){
  blocks to execute when condition hold
} else{
  blocks to execuse when condition fails
}

Here is an example of if-else statement:

x <- 1
y <- 2
if(x<y){
  print("Yes!")
} else{
  print("No~")
}
## [1] "Yes!"

In this example, the program printed No~ since the condition hold.

3.2.3 Application: Nested-if statement

Different blocks of code will be executed depends on whether conditions are satisfied. Note that conditions are checked from the top to the bottom.

x <- 1
y <- 2
if(x<y){
  print("Yes!")
} else if (x==y){
  print("Oh.")
} else {
  print("No~")
}
## [1] "Yes!"

3.2.4 Application: Checking Data Type

One important usage of conditional statement is to check whether the data for calculation is correct.

Very often, we only want to execute the code if the data point exists. We can use is.na(). It will return true if it is NA; otherwise false.

if(!is.na(x)){
  do.something
}

Another related function is to check if the data type is number. The function is.numeric() returns true if it is numerical variable; otherwise false.

3.2.5 Application: Missing data

Note that R reports error if there is an NA in the statement.

x <- NA
x > 0
## [1] NA

Very often, we want to set ignore those case with missing data (NA). Then we will use isTRUE()

x <- NA
isTRUE(x > 0)
## [1] FALSE