Skip to content

Lesson 2 Exercise Questions: Base R syntax, objects, and data types

  1. Let's use some functions.

    a. Use sum() to add the numbers from 1 to 10.

    Solution

    sum(1:10)
    

    b. Compute the base 10 logarithm of the elements in the following vector and save to an object called logvec: c(1:10).

    Solution

    logvec<- log10(c(1:10))
    

    c. What does the function paste() do? Use it to combine the following vectors. Use an _ as a separator.

    id <- LETTERS[1:5]
    idnum<- c(1,3,6,9,12)
    

    Solution

    paste(id,idnum,sep="_")
    

    d. What does the function identical() do? Use it to compare the following vectors.

    a<-seq(2,10,by=2)
    b<-c(2,4,6,8,10)
    

    Solution

    #tells us whether the two vectors are the same
    identical(a,b)
    

  2. What is the value of each object? You should know the value without printing the value of the object.

    mass <- 47.5            # mass?
    age  <- 122             # age?
    mass <- mass * 2.0      # mass?
    age  <- age - 20        # age?
    mass_index <- mass/age  # mass_index?
    

    (Question taken from https://carpentries-incubator.github.io/bioc-intro/23-starting-with-r/index.html)

  3. Create the following objects; give each object an appropriate name.

    a. Create an object that has the value of the number of bones in the adult human body.

    b. Create an object containing the names of four different bones.

    c. Create an object with values 1 to 100.

    Solution

    bone_num<- 206
    bone_names<- c("talus","calcaneus","tibia","fibula") 
    values<-c(1:100) 
    

  4. Vectors include data of a single type, so what happens if we mix different types? Use typeof() to check the data type of the following objects.

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

    Solution

    #These were coerced into a single data type
    typeof(num_char)
    num_char
    typeof(num_logical)
    num_logical
    typeof(char_logical)
    char_logical
    typeof(tricky)
    tricky
    
    (Question taken from https://carpentries-incubator.github.io/bioc-intro/23-starting-with-r/index.html)

  5. Using indexing, create a new vector named combined that contains:

    The 2nd and 3rd value of num_char.
    The last value of char_logical.
    The 1st value of tricky.

    Solution

    combined <- c(num_char[2:3], char_logical[length(char_logical)],
                tricky[1])