List in R Language

In R language, a list is an object that consists of an ordered collection of objects known as its components. A list in R Language is structured data that can have any number of modes (types) or other structured data. That is, one can put any kind of object (like vector, data frame, character object, matrix, and/ or array) into one list object. An example of a list is

x <- list(c(1,2,3,5), c("a", "b", "c", "d"), c(T, T, F, T, F), matrix(1:9, nr = 3) )

that contains 4 components, three of them are vectors (numeric, string, and logical) and one of them is a matrix.

List in R Language

Converting Objects to List in R Language

An object can also be converted to a list by using the as.list( ) function. For vector, the disadvantage is that each element of the vector becomes a component of that list. For example,

as.list (1: 10)

Extract components from a list

The operator [[ ]] (double square bracket) is used to extract the components of a list. To extract the second component of the list, one can write at R prompt,

list[[2]]

Using the [ ] operator returns a list rather than the structured data (the component of the list). The component of the list need not be of the same mode. The components are always numbered. If x1 is the name of a list with four components, then individual components may be referred to as x1[[1]], x1[[2]], x1[[3]], and x1[[4]].

If components of a list are defined then these components can be extracted by using the names of components. For example, a list with named components is

x1 <- list(a = c(1,2,3,5), b = c("a", "b", "c", "d"), c = c(T, T, F, T, F), 
d = matrix(1:9, nr = 3) )

To extract the component a, one can write

x1$a
x1["a"]
x1[["a"]]

To extract more than one component, one can write

x[c(1,2)]     #extract component one and two
x[-1]         #extract all component except 1st
x[[c(2,2)]]   #extract 2nd element of component two
x[[c(2:4)]]   #extract all elements of component 2 to 4

https://itfeature.com

Leave a Reply