Web EndMemo

R List Data Type


R list data type refers to an object consisting of an ordered collection of elements. The elements may be of different mode or type.


Let's create a list containing numeric, character and vector data types:

>x <- list(batch=3,label="Lung Cancer Patients", subtype=c("A","B","C"))
>x
$batch
[1] 3

$label
[1] "Lung Cancer Patients"

$subtype
[1] "A" "B" "C"
>is.list(x)
[1] TRUE

The elements of list data type are indexed by numbers. e.g. x[[1]] refers to 3 ...
>x[[1]]
[1] 3
x[[2]]
[1] "Lung Cancer Patients"
x[[3]]
[1] "A" "B" "C"
x[[3]][2]
[1] "B"
The elements of list can also be accessed by their names.
>x$subtype
[1] "A" "B" "C"
>x[["subtype"]]
[1] "A" "B" "C"

The statement length() calculate the total elements number of a list.
>length(x)
[1] 3

Function c() can be used for concatenating two or more lists.
>y <- list(operator="Mary",location="New York")
>z <- list(cost=1000.24,urgent="yes")
>final_list <- c(x,y,z)
>final_list
$batch
[1] 3

$label
[1] "Lung Cancer Patients"

$subtype
[1] "A" "B" "C"

$operator
[1] "Mary"

$location
[1] "New York"

$cost
[1] 1000.24

$urgent
[1] "yes"

List to data frame: as.data.frame() can coerce a list into a data frame, providing that the components of the list conforms to the restrictions of a data frame.
>y <- as.data.frame(x)
>y
  batch                label subtype
1     3 Lung Cancer Patients       A
2     3 Lung Cancer Patients       B
3     3 Lung Cancer Patients       C

List to matrix: as.matrix() can coerce a list into a matrix, providing that the components of the list conforms to the restrictions of a matrix.
>y <- as.matrix(x)
>y
        [,1]                  
batch   3                     
label   "Lung Cancer Patients"
subtype Character,3