In general, most of the objects you would interact with as a user would tend to be a vector; e.g numeric vector, logical vector. These objects can only take in a single type of variable (a numeric vector can only have numbers inside it).
A list would be able to store any type variable in it, making it to the generic object that can store any type of variables we would need.
Example of initializing a list
exampleList1 <- list('a', 'b')
exampleList2 <- list(1, 2)
exampleList3 <- list('a', 1, 2)
In order to understand the data that was defined in the list, we can use the str function.
str(exampleList1)
str(exampleList2)
str(exampleList3)
Subsetting of lists distinguishes between extracting a slice of the list, i.e. obtaining a list containing a subset of the elements in the original list, and extracting a single element. Using the [
operator commonly used for vectors produces a new list.
# Returns List
exampleList3[1]
exampleList3[1:2]
To obtain a single element use [[
instead.
# Returns Character
exampleList3[[1]]
List entries may be named:
exampleList4 <- list(
num = 1:3,
numeric = 0.5,
char = c('a', 'b')
)
The entries in named lists can be accessed by their name instead of their index.
exampleList4[['char']]
Alternatively the $
operator can be used to access named elements.
exampleList4$num
This has the advantage that it is faster to type and may be easier to read but it is important to be aware of a potential pitfall. The $
operator uses partial matching to identify matching list elements and may produce unexpected results.
exampleList5 <- exampleList4[2:3]
exampleList4$num
# c(1, 2, 3)
exampleList5$num
# 0.5
exampleList5[['num']]
# NULL
Lists can be particularly useful because they can store objects of different lengths and of various classes.
## Numeric vector
exampleVector1 <- c(12, 13, 14)
## Character vector
exampleVector2 <- c("a", "b", "c", "d", "e", "f")
## Matrix
exampleMatrix1 <- matrix(rnorm(4), ncol = 2, nrow = 2)
## List
exampleList3 <- list('a', 1, 2)
exampleList6 <- list(
num = exampleVector1,
char = exampleVector2,
mat = exampleMatrix1,
list = exampleList3
)
exampleList6
#$num
#[1] 12 13 14
#
#$char
#[1] "a" "b" "c" "d" "e" "f"
#
#$mat
# [,1] [,2]
#[1,] 0.5013050 -1.88801542
#[2,] 0.4295266 0.09751379
#
#$list
#$list[[1]]
#[1] "a"
#
#$list[[2]]
#[1] 1
#
#$list[[3]]
#[1] 2