Lists
Introduction
In the previous post, we learnt about matrices. In this post, we will learn about lists. Lists are very useful as they are heterogeneous i.e. they can contain different data types. If you remember, vectors and matrices are homogeneous i.e. they can contain only one type of data. If you include different data types, they will all be coerced to the same type. With lists, it is different. We learnt how to create lists briefly in the previous post while naming the rows and columns of a matrix. In this post, we will delve deeper into lists.
- how to create lists
- access list elements
- name list elements
- coerce other R objects to list
- coerce list to other R objects
Creating Lists
To create a list, we use the list() function. Let us create a simple list to demonstrate how they can contain different data types.
# numeric vector
vect1 <- 1:10
# character vector
vect2 <- c('Jack', 'John', 'Jill')
# logical vector
vect3 <- c(TRUE, FALSE)
# matrix
mat <- matrix(data = 1:9, nrow = 3)
# list
l <- list(vect1, vect2, vect3, mat)
l
## [[1]]
## [1] 1 2 3 4 5 6 7 8 9 10
##
## [[2]]
## [1] "Jack" "John" "Jill"
##
## [[3]]
## [1] TRUE FALSE
##
## [[4]]
## [,1] [,2] [,3]
## [1,] 1 4 7
## [2,] 2 5 8
## [3,] 3 6 9
If you observe the output, all the elements of the list retain their data types. Now let us learn how to access the elements of the list.
Access List Elements
You can access the elements of a list using the following operators:
-
[[ -
[ -
\(</code></li> </ul> <p>Let us try them one by one.</p> <pre class="r"><code># using [[ l[[1]]</code></pre> <pre><code>## [1] 1 2 3 4 5 6 7 8 9 10</code></pre> <pre class="r"><code># using [ l[1]</code></pre> <pre><code>## [[1]] ## [1] 1 2 3 4 5 6 7 8 9 10</code></pre> <p><code>[[</code> returns a vector while <code>[</code> returns a list. The <code>\)operator can be used only when we have named elements in the list. Let us add names to the elements. Use thenames()function to add names to the list.# named elements names(l) <- c('vect1', 'vect2', 'vect3', 'mat') l## $vect1 ## [1] 1 2 3 4 5 6 7 8 9 10 ## ## $vect2 ## [1] "Jack" "John" "Jill" ## ## $vect3 ## [1] TRUE FALSE ## ## $mat ## [,1] [,2] [,3] ## [1,] 1 4 7 ## [2,] 2 5 8 ## [3,] 3 6 9# use $ l$vect1## [1] 1 2 3 4 5 6 7 8 9 10# use [[ l[['vect1']]## [1] 1 2 3 4 5 6 7 8 9 10# use [ l['vect1']## $vect1 ## [1] 1 2 3 4 5 6 7 8 9 10