A list can be thought of as zero or more data elements (of any type), kept in order.
The elements can be accessed by their position (or index): first element, second element, …
Typically the elements are also named and consequently can be also accessed by the names.
A list allows to keep together related information.
For example, functions often return lists when they calculate more than one value at once.
Type the following code to manualy create a list and store it in a variable person
:
person <- list(
name = "Bob",
age = 44,
children = c( "Amy", "Dan", "Eve" )
)
Now, check how the person
list is printed:
person
$name
[1] "Bob"
$age
[1] 44
$children
[1] "Amy" "Dan" "Eve"
Test the class of person
:
class( person )
[1] "list"
Try the function str
(structure) on person
.
It gives a compact display of data stored in a variable and is useful for a list
:
str( person )
List of 3
$ name : chr "Bob"
$ age : num 44
$ children: chr [1:3] "Amy" "Dan" "Eve"
Use length
to find the number of elements in a list:
length( person )
[1] 3
Elements of a list can be accessed by their position (first, second, …) with help of [[...]]
(double bracket) operator.
Try the following to get the first and the last elements:
person[[1]]
[1] "Bob"
person[[ length(person) ]]
[1] "Amy" "Dan" "Eve"
You may indeed observe that the elements of the person
list are of different classes:
class( person[[1]] )
[1] "character"
class( person[[2]] )
[1] "numeric"
To get names of all elements of a list enter:
names( person )
[1] "name" "age" "children"
Each of these names can be used with the [[...]]
operator to get/set an element by name:
person[[ 'name' ]]
[1] "Bob"
person[[ 'children' ]]
[1] "Amy" "Dan" "Eve"
Try to add a new element to the list using:
person[[ 'smoker' ]] <- TRUE
person
$name
[1] "Bob"
$age
[1] 44
$children
[1] "Amy" "Dan" "Eve"
$smoker
[1] TRUE
and next change the element:
person[[ 'smoker' ]] <- FALSE
person
$name
[1] "Bob"
$age
[1] 44
$children
[1] "Amy" "Dan" "Eve"
$smoker
[1] FALSE
and then remove that element from the list:
person[[ 'smoker' ]] <- NULL
person
$name
[1] "Bob"
$age
[1] 44
$children
[1] "Amy" "Dan" "Eve"
Note what happens when you try to access a not present element:
person[[ 'isMarried' ]]
NULL
Copyright © 2023 Biomedical Data Sciences (BDS) | LUMC