If you need to work on several objects at the same time or need for any reason to gather objects in a single collection, you may create a list object. And this is done using the function list(). In the following example, we’ll make a list that contains the new objects a
, b
, and c
which are respectively the integer “42”, the word “Whatever” and a 3×3 matrix containing numbers from 1 to 9, respectively.
[code language=”r”]
a <- 42
b <- "Whatever"
c <- matrix(1:9, nrow=3, ncol=3)
my.list <- list(a,b,c)
my.list
[/code]
As shown in the picture above, list()
has gathered all three objects and displayed them in the correct sequence, with the position of each of these objects indicated between double-brackets . This, again, is helpful to retrieve one of the objects in the list. In the picture below, we retrieve the second object in my.list
:
[code language=”r”]
my.list[2]
[/code]
It becomes also possible to name the objects in the list using the function names() as follows:
[code language=”r”]
names(my.list) <- c("my number", "my word", "my matrix")
my.list
[/code]
Note that the name of the list members between '
and following a $
.