if-else Statements & Basic Plotting

Ha Khanh Nguyen

if Statement

  • An if statement tells R to do a certain task for a certain case.
  • In English, you would say “If <condition> is true, do <steps>!”
  • In R, you would say:
  • condition object should be a logical statement/test or an R expression that evaluates to a single TRUE or FALSE.

  • If condition is TRUE,
    • R will run all the code that appears between the curly brackets {} following the if statement.
  • If condition is FALSE,
    • R will skip the code between the curly brackets without running it.

Below is an example of an if statement to make sure a number num is positive.

  • In the case, num < 0 is TRUE:
## [1] 2
  • In the case, num < 0 is FALSE:
## [1] 4
  • Quiz 1: What will the following code return?
  • Quiz 2: What will the following code return?
  • Quiz 3: What will the following code return?

else Statement

  • if statement tells R what to do when the condition is TRUE.
  • else statement tells R what to do when the condition is FALSE.
  • Example: Write a function for rounding a number to the nearest whole number.
  • Isolate the decimal component with trunc() function.
## [1] 0.14
  • Use if else to round the number (up or down):
## [1] 3
  • Write the rounding function:
## [1] 3
## [1] 3
## [1] 5
## [1] 5
  • Another example
## [1] "Tie."

Basic Plots

Histogram

  • Change the plot title

  • Change x-axis label

  • Change the y-axis (from frequency) to probability/density

  • Change how the histogram is graphed (by changing the column width):
    • The argument breaks in hist() can take one of the following:
      • a vector giving the breakpoints between histogram cells,
      • a function to compute the vector of breakpoints,
      • a single number giving the number of cells for the histogram,
      • a character string naming an algorithm to compute the number of cells (see ‘Details’),
      • a function to compute the number of cells.

  • Let’s add some color to this histogram!

  • A bit too much?

  • Make it looks “professional”!

To-do

References