My Coding >
Software >
R >
R lists
R lists
List is a structure in R to store data of different types.
Initialization of lists in R
To initialize list it is necessary to use function list()
> a < list(3, "text", TRUE, 5.5, c(4,5))
> typeof(a)
[1] "list"
> typeof(a[1])
[1] "list"
> typeof(a[[1]])
[1] "double"
> typeof(a[[2]])
[1] "character"
To call individual element from the list, it is necessary to use double square brackets
> a[[1]]
[1] 3
[[2]]
[1] "text"
> a[[5]][2]
[1] 5
Key/value lists in R
It is possible to create key/value list in R with function list()
> b < list(a=c(1,2,3), b=c(4,5,6), c=c(7,8,9))
It is possible to access elements of this list with using symbol $
> b # Full content
$a
[1] 1 2 3
$b
[1] 4 5 6
$c
[1] 7 8 9
> b$a # access to individual vector
[1] 1 2 3
> b$a[1] # access to individual element in vector
[1] 1
> b$a[2] # access to individual element in vector
[1] 2
> b$d < c(10,11,12) # it is possible to add new keyvalue pair
Function to work with keyvalue list in R
The main function to work with lists are:  str()  structure of the lists
 length()  list length
 lapply()  apply function to each vector and return keyvalue lists
 sapply()  apply function to each vector and return keyvalue vector
> str(b)
List of 4
$ a: num [1:3] 1 2 3
$ b: num [1:3] 4 5 6
$ c: num [1:3] 7 8 9
$ d: num [1:3] 10 11 12
> length(b)
[1] 4
> lapply(b, mean)
$a
[1] 2
$b
[1] 5
$c
[1] 8
$d
[1] 11
> sapply(b, min)
a b c d
1 4 7 10
Published: 20211110 10:53:37 Updated: 20211110 12:19:46
