Introduction
A list is an indexed set of objects, which can include different data type, even lists. Its power and utility are from its generality. In R, it is often used to collect and store complicated function output. The dataframes are special kinds of lists.
A list is created using the list(...)
, wich comma-seperated arguments. Single square brackets are used to select a sublist, double square brackerts are used to extract a single element.
> my.list<-list("one",TRUE,3,c("f","o","u","r"))
> my.list
[[1]]
[1] "one"
[[2]]
[1] TRUE
[[3]]
[1] 3
[[4]]
[1] "f" "o" "u" "r"
You can see the list contain diffent type elements.
> mode(my.list)
[1] "list"
You can see the type of varible is list type.
> my.list[[2]]
[1] TRUE
We can use the double square brackerts to extract a single element.
> mode(my.list[[3]])
[1] "numeric"
> mode(my.list[2])
[1] "list"
Single square brackets get a sublist. Double square get a vector element.
> my.list<- list(first="one",second=TRUE,third=3,fourth=c("f","o","u","r"))
> names(my.list)
[1] "first" "second" "third" "fourth"
> str(my.list)
List of 4
$ first : chr "one"
$ second: logi TRUE
$ third : num 3
$ fourth: chr [1:4] "f" "o" "u" "r"
We can set the name for the sublists.
> names(my.list)<-c("First element","Second element","Third element","Fourth element")
> my.list$`Second element`
[1] TRUE
We can update the names of sublists.
> x <- list(1, c(2, 3), c(4, 5, 6),list(c(1,2,3,4),c("hello A","hello B")))
> x
[[1]]
[1] 1
[[2]]
[1] 2 3
[[3]]
[1] 4 5 6
[[4]]
[[4]][[1]]
[1] 1 2 3 4
[[4]][[2]]
[1] "hello A" "hello B"
We can add a list into a list.
> unlist(x)
[1] "1" "2" "3" "4" "5" "6" "1" "2"
[9] "3" "4" "hello A" "hello B"
We can flat a list to get all the vector elements. All the sublists will covert into a list.
unlist(x,recursive = F)
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] 4
[[5]]
[1] 5
[[6]]
[1] 6
[[7]]
[1] 1 2 3 4
[[8]]
[1] "hello A" "hello B"
We can just flat one level.
The OLS output is a list and can be manipulated using list operations.
> lm.xy<-lm(y~x,data=data.frame(x=1:5,y=1:5))
> names(lm.xy)
[1] "coefficients" "residuals" "effects" "rank" "fitted.values"
[6] "assign" "qr" "df.residual" "xlevels" "call"
[11] "terms" "model"
> mode(lm.xy)
[1] "list"
Exericses to get a matched result in list.
premierships <- list(Adelaide = c(1997, 1998),
Carlton = c(1906, 1907, 1908, 1914, 1915, 1938, 1945, 1947,1968, 1970, 1972, 1979, 1981, 1982, 1987, 1995),
Collingwood = c(1902, 1903, 1910, 1917, 1919, 1927, 1928, 1929,1930, 1935, 1936, 1953, 1958, 1990))
year<-1917
for (i in 1:length(premierships)) {
if (year %in% premierships[[i]]){
winner<-names(premierships)[i]
}
}
> winner
[1] "Collingwood"
We build a list, we can use for loop to get the matched result.