Learning Objectives

Reading

### R programming

Lecture Notes


Exercises

  1. -- R-001 --

    What are the values after each statement in the following?

    mass <- 47.5            # mass?
    age  <- 122             # age?
    mass <- mass * 2.0      # mass?
    age  <- age - 20        # age?
    mass_index <- mass/age  # mass_index?
    
  2. -- R-002 --

    We’ve seen that atomic vectors can be of type character, numeric (or double), integer, and logical. But what happens if we try to mix these types in a single vector?

    What will happen in each of these examples? (hint: use class() to check the data type of your objects):

    num_char <- c(1, 2, 3, "a")
    num_logical <- c(1, 2, 3, TRUE)
    char_logical <- c("a", "b", "c", TRUE)
    tricky <- c(1, 2, 3, "4")
    

    Why do you think it happens?

    How many values in combined_logical are “TRUE” (as a character) in the following example:

    num_logical <- c(1, 2, 3, TRUE)
    char_logical <- c("a", "b", "c", TRUE)
    combined_logical <- c(num_logical, char_logical)
    

    You’ve probably noticed that objects of different types get converted into a single, shared type within a vector. In R, we call converting objects from one class into another class coercion. These conversions happen according to a hierarchy, whereby some types get preferentially coerced into other types. Can you draw a diagram that represents the hierarchy of how these data types are coerced?

  3. -- R-003 --

    Using this vector of heights in inches, create a new vector, heights_no_na, with the NAs removed.

    heights <- c(63, 69, 60, 65, NA, 68, 61, 70, 61, 59, 64, 69, 63, 63, NA, 72, 65, 64, 70, 63, 65)
    
    • Use the function median() to calculate the median of the heights vector.
    • Use R to figure out how many people in the set are taller than 67 inches.