Lists
Featured in 1 main post
In R, a list is a group of elements of any type. In contrast to a vector, there is no limitation to the type of elements in a list. A list can contain vectors, data tables, lists, other objects, or any combination of them.
Combine elements in a list
To construct a list from its constituent elements, all we have to do is use the list function, with the desired elements in brackets. Below, we’ll create two vectors a and b and then put them, along with one more element, in a list named x:
a <- c(5,6,4)
b <- c("Jack","Jill")
x <- list(a,b,6)
Let’s have a look at our new list:
x
## [[1]]
## [1] 5 6 4
##
## [[2]]
## [1] "Jack" "Jill"
##
## [[3]]
## [1] 6
The index of each list element is shown in double square brackets (e.g. [[1]]). The [1] on the left side of each vector is the index of its own left-most element, as vectors are commonly displayed.
Another way to examine a list is the str function, displaying the list’s structure:
str(x)
## List of 3
## $ : num [1:3] 5 6 4
## $ : chr [1:2] "Jack" "Jill"
## $ : num 6
As we see, x is a list of 3 elements:
-
a
numericvector of length 3 -
a
charactervector of length 2 -
a
numericvector of length 1
Accessing list elements
To get one or more elements from a list, write a numeric vector with their index numbers in square brackets. For example, to get the 2nd element of x:
x[2]
## [[1]]
## [1] "Jack" "Jill"
However, x[2] is not a vector and we cannot use it as one. This is because an index number in single square brackets returns a subset of the list - i.e. a list of one element. And a list of one element is not the same as purely that one element!
To get a pure single element instead of a list subset, write the index in double square brackets:
x[[2]]
## [1] "Jack" "Jill"