5.2 Conditional

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

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

Example of if-else statement

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

Exercises

  1. Write a function f(x) that returns absolute value of x.

    • If x is positive, then f(x) =x.

    • If x is negative, then f(x) = -x.

  2. Write a function f(x) that returns CAP given exam score x.

    • If x=90, then CAP is 5.

    • If x is between 80 and 90, then CAP is 4.

    • If x is between 70 and 80, then CAP is 3.

    • If x is less than 70, then CAP is 2.

  3. Write a function f(x,y) that returns grade using test score x and exam score y.
    • If x+y is no less than 90 and y is no less than 40, then grade is A+.
    • If x+y is no less than 80 but less than 90, then CAP is A.
    • If x+y is no less than 70 but less than 80, then CAP is A-.
    • If x+y is less than 70, then CAP is B+.

5.2.1 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.

5.2.2 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