Lists
What are Lists?
The list
object is the most flexible of
R’s basic objects. It has no size constraints, meaning
you can store objects of different sizes within it.
Similarly, it has no type constraints, allowing you to
store a wide variety of objects. Each element in the
list can have a name. These names can be accessed using the
names()
function, just like with vectors.
my_list <- list(a_vector = 1:5,
a_matrix = matrix(8:13, nr = 2),
some_letters = LETTERS[10:15])
my_list
names(my_list)
The size of the list (the number of stored objects) is given, as with
vectors, by the length()
function.
length(my_list)
Indexing Lists
The Indexing Function ‘[’
Note that in the case of lists, the indexing function (“[”) returns a sublist. It is therefore useful for creating a new list that is a subset of the original list.
sub_list <- my_list[c(1,3)]
is(sub_list)
sub_list
The Indexing Function ‘[[’
To directly access the elements contained in the list, you need to use the “[[” indexing function and pass it either a numeric value or the name of a target element as an argument. This function only accepts an atomic vector (containing a single element) as input.
# Mêmes résultats
my_list[[1]]
my_list[['a_vector']]
The Indexing Function $
As with data.frame
objects, you can also use the ‘$’
operator to index the list.
# Mêmes résultats
my_list$a_vector
- Using the indexing functions, extract the \(5^{th}\) position of the vector
a_vector
contained inmy_list
. Store the result in the variablea
. - Using the indexing functions, extract the cell at row 2 / column 2
of the matrix
a_matrix
. Store the result in the variableb
.
my_list <- list(a_vector = 1:5,
a_matrix = matrix(8:13, nr = 2),
some_letters = LETTERS[10:15])
my_list <- list(a_vector = 1:5,
a_matrix = matrix(8:13, nr = 2),
some_letters = LETTERS[10:15])
# Exo a: solution 1
a <- my_list[['a_vector']][5]
# Exo a: solution 2
v <- my_list[['a_vector']]
a <- v[5]
# Exo a: solution 3
v <- my_list$a_vector
a <- v[5]
# Exo a: solution 4
a <- my_list$a_vector[5]
# Exo b (your turn to find
# additional solutions)
b <- my_list$a_matrix[2, 2]
- Using the indexing functions, extract the \(5^{th}\) position of the vector
a_vector
contained in the nested list. Store the result in the variablea
. - Using the indexing functions, extract the cell at row 2 / column 2
of the matrix
a_matrix
contained in the nested list. Store the result in the variableb
.
my_list <- list(A=list(a_vector = 1:5,
a_matrix = matrix(8:13, nr = 2)),
B=list(some_letters = LETTERS[10:15],
other_letters = LETTERS[18:26])
)
my_list <- list(A=list(a_vector = 1:5,
a_matrix = matrix(8:13, nr = 2)),
B=list(some_letters = LETTERS[10:15],
other_letters = LETTERS[18:26])
)
a <- my_list$A$a_vector[5]
b <- my_list$A$a_matrix[2, 2]
End of the section
Thank you for following this tutorial.