Activity: practice with lists

Practice with lists

  1. Each of the following lists contains the vector c(2, 7, 9). Determine the correct list indexing syntax to extract that vector from the list (your code should return just the vector, not a list containing the vector).
x1 <- list(c(2, 7, 9))
x2 <- list(list(c(2, 7, 9)))
x3 <- list(c(2, 7, 9), list("a", "b"))
x4 <- list(c("a", "b"), list(list(c(2, 7, 9))))

Solution:

x1[[1]]
[1] 2 7 9
x2[[1]][[1]]
[1] 2 7 9
x3[[1]]
[1] 2 7 9
x4[[2]][[1]][[1]]
[1] 2 7 9
  1. Create a list x5 such that the vector c(2, 7, 9) can be extracted with x5[[3]][[2]][[1]].

Solution: Here is one example:

x5 <- list("a", "b", list("c", list(c(2, 7, 9))))
x5[[3]][[2]][[1]]
[1] 2 7 9
  1. Create a list x in R such that:
  • x[[1]] returns the function mean
  • x[[2]] returns the function sd
  • x[[3]][[1]] returns the vector c(0, 1, 2)
  • x[[3]][[2]] returns a function which calculates the cube root

Solution:

x <- list(mean, sd, list(c(0, 1, 2), function(y) y^(1/3)))