Lists
What are lists?
Unlike vectors, R lists can hold components of different data types.
> my_list <- list(2,"c",TRUE) > my_list
//Output Below
[[1]] [1] 2 [[2]] [1] "c" [[3]] [1] TRUE
Nice! we just created a list using the list()
function and
assigned it a numeric, a character, and a logical element type.
More lists
Lists can also contain more complex data components such as whole vectors, matrices or data frames.
> vec <- 1:6 > mat <- matrix(1:6,nrow=2) > df <- data.frame(mat) > list(vec, mat, df)
//Output Below
[[1]] [1] 1 2 3 4 5 6 [[2]] [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 [[3]] X1 X2 X3 1 1 3 5 2 2 4 6
Great! We can see that lists are very flexible. We could even store a list inside another list if we wanted to.
Renaming list components
By default, list component names are simply their indices.
Let's rename the first component of our list to vector
.
> vec <- 1:6 > mat <- matrix(1:6,nrow=2) > df <- data.frame(mat) > my_list <- list(vector=vec,matrix=mat,dframe=df)
//Output Below
$vector [1] 1 2 3 4 5 6 $matrix [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 $dframe X1 X2 X3 1 1 3 5 2 2 4 6
Pretty straightforward, right?
Extracting list components
We can extract list components by using double brackets around the index or the name. We can also use the $
sign with the name.
Let's see if we can extract a component by using it's index.
> my_list <- list(int=2,vec=1:6,bool=TRUE) > my_list[[2]]
//Output Below
[1] 1 2 3 4 5 6
Nice! Lists provide us with many different ways of extracting components.
Extracting by name
Let's extract the same element, only this time, let's use it's name.
> my_list <- list(int=2,vec=1:6,bool=TRUE) > my_list$vec
//Output Below
[1] 1 2 3 4 5 6
Exactly! We just need to use the $
symbol alongside the name.
Further subsetting
What if we want to extract a 3rd element of a vector that belongs to a list?
> my_list <- list(int=2,vec=1:6,bool=TRUE) > print(my_list[[2]][3])
//Output Below
[1] 3
Awesome! The first [[2]]
indicates the vector element in the list, while the [3]
indicates the element we want from that vector.
Appending components
We can add a component of any type to our list by using the c()
function.
> my_list <- list(int=2,vec=1:6,bool=TRUE) > my_list <- c(my_list,TRUE) > my_list
//Output Below
$int [1] 2 $vec [1] 1 2 3 4 5 6 $bool [1] TRUE [[4]] [1] TRUE
See that? R automatically converts other elements in the c()
function into list elements.
Comments