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.
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:
## [1] "Yes!"
In this example, the statement will executed since the condition holds.
Alternatively, let us see our second example:
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:
## [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.
## [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.
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.