List
A list is a collection of multiple objects which can be a scalar, a vector, a matrix, etc. Each object in a list can have its own name.
Create a list
To create a list, the function list()
can be used as shown in the examples below.
> x <- list('a'=3, 'b'=c(1,2), 'm'=array(1:6, dim=c(3,2))) > x $a [1] 3 $b [1] 1 2 $m [,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6 > > a <- 3 > b <- c(1,2) > m <- array(1:6, dim=c(3,2)) > > y <- list(a, b, m) > y [[1]] [1] 3 [[2]] [1] 1 2 [[3]] [,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6 >
Access the object of a list
There are at least two ways to access the objects in a list. First, each object in the list has an index according to its order, which can be used to access that object. For example, x[[1]]
will access the first object in the list. Note that [[ ]]
instead of [ ]
is used here. Second, the name of the object can be used to access it. For example, x$a
will access a
in the list. Note that a dollar sign $
is added between the name of the list and the name of the object.
> x <- list('a'=3, 'b'=c(1,2), 'm'=array(1:6, dim=c(3,2))) > > x[[3]] [,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6 > > x$m [,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6 >
To cite the book, use:
Zhang, Z. & Wang, L. (2017-2025). Advanced statistics using R. Granger, IN: ISDSA Press. https://doi.org/10.35566/advstats. ISBN: 978-1-946728-01-2.
To take the full advantage of the book such as running analysis within your web browser, please subscribe.