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"

> typeof(x)
[1] "list"
> length(x)
[1] 3
> is.list(x)

[1] TRUE

str() can be used to quick check the structure of a list:

> str(x)
List of 3
$ batch  : num 3
$ label  : chr "Lung Cancer Patients"
$ subtype: chr [1:3] "A" "B" "C"


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"

Use names() function to get all the index names of a list:

> names(x)

[1] "batch"   "label"   "subtype"


The statement length() calculate the total elements number of a list.

> length(x)

[1] 3

To delete an element of list, just assign its value to NULL:

> x$batch <- NULL
> x
$label
[1] "Lung Cancer Patients"
$subtype
[1] "A" "B" "C"


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"

as.list() can convert factor, data.frame etc into list:

> BOD
  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8
> as.list(BOD)
$Time
[1] 1 2 3 4 5 7
$demand
[1]  8.3 10.3 19.0 16.0 15.6 19.8
attr(,"reference")
[1] "A1.4, p. 270"
> x <- factor(c(1,3,5,1,3,5,3))
> as.list(x)
[[1]]
[1] 1
Levels: 1 3 5
[[2]]
[1] 3
Levels: 1 3 5
[[3]]
[1] 5
Levels: 1 3 5
[[4]]
[1] 1
Levels: 1 3 5
[[5]]
[1] 3
Levels: 1 3 5
[[6]]
[1] 5
Levels: 1 3 5
[[7]]
[1] 3
Levels: 1 3 5


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

endmemo.com © 2024  | Terms of Use | Privacy | Home