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. In this chapter, 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
10.2 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.
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.
10.3 Access List Elements
You can access the elements of a list using the following operators:
[[
[
$
Let us try them one by one.
# using [[l[[1]]
[1] 1 2 3 4 5 6 7 8 9 10
# using [l[1]
[[1]]
[1] 1 2 3 4 5 6 7 8 9 10
[[ extracts the element itself (which may be a vector, matrix, data frame, or nested list), while [ returns a new list containing the selected element(s). The $ operator can be used only when we have named elements in the list. Let us add names to the elements. Use the names() function to add names to the list.
# named elementsnames(l) <-c('vect1', 'vect2', 'vect3', 'mat')l