About
The list in R may contain elements of the different class (just like a data frame)
Collection of object which must have the same class of objects are:
data.tables and data.frames are internally lists with all its columns of equal length and with a class attribute.
Articles Related
Syntax
myList = list(object,object,...)
Example
- List
> v = list("Nico has",40,"year")
> v
[[1]]
[1] "Nico has"
[[2]]
[1] 40
[[3]]
[1] "year"
- List of vector (for the dimension of a matrix
dimnames = list(c("Row1", "Row2"), c("Col1", "Col2", "Col3"))
> dimnames
[[1]]
[1] "Row1" "Row2"
[[2]]
[1] "Col1" "Col2" "Col3"
Attributes
Names
names: Functions to get or set the variable name of a value.
l = list(name = "Nico", age = 40)
l
$name
[1] "Nico"
$age
[1] 40
> names(l)
[1] "name" "age"
- You can access the value then by name
l$name
[1] "Nico"
How to
subset
Example using the subset operators
> l = list(name = c("Nico","Mad","Mel"), age = c(40,7,4), colour=c("Red","Blue","Parse"))
> l
$name
[1] "Nico" "Mad" "Mel"
$age
[1] 40 7 4
$colour
[1] "Red" "Blue" "Parse"
- Indexing by key (return a list)
> l[1]
$name
[1] "Nico" "Mad" "Mel"
- Indexing by Name (return a list)
> l["name"]
$name
[1] "Nico" "Mad" "Mel"
- Indexing by vector (return a list)
> name <- "name"
> l[name]
$name
[1] "Nico" "Mad" "Mel"
- Indexing by key and returning a vector
> l[[1]]
[1] "Nico" "Mad" "Mel"
- Indexing by name and returning a vector
> l$name
[1] "Nico" "Mad" "Mel"
# of
> l[["name"]]
[1] "Nico" "Mad" "Mel"
- Indexing by vector and returning a vector
> name <- "name"
> l[[name]]
[1] "Nico" "Mad" "Mel"
- Retrieving the first and third elements in the list
> l[c(1,3)]
$name
[1] "Nico" "Mad" "Mel"
$colour
[1] "Red" "Blue" "Parse"
- Retrieving the third element of the first element
l[[c(1,3)]]
[1] "Mel"
# of
> l[[1]][[3]]
[1] "Mel"
- Partial Matching when retrieving a vector
> l[["n"]]
NULL
> l[["n", exact=FALSE]]
[1] "Nico" "Mad" "Mel"
Apply
lapply apply a function over an list.
Function
Class
> class(v)
[1] "list"
Length
> l = list("Nico has",40,"year")
> length(l)
[1] 3
Structure
Data Structure
> l = list("Nico has",40,"year")
> str(v)
List of 3
$ : chr "Nico has"
$ : num 40
$ : chr "year"