Lists

Table of Contents

Overview

family <- list(name="Fred", wife="Mary", no.children=3, child.ages=c(4,7,9))
family$name
family[["wife"]]  # element
family["wife"]    # sublist
[1] "Fred"
[1] "Mary"
x <- list(1, 2, 3)
x[4] <- list(4)
x
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

x <- list("a", "b")
y <- list("x", "y")
c(x, y)  # concat
[[1]]
[1] "a"

[[2]]
[1] "b"

[[3]]
[1] "x"

[[4]]
[1] "y"

Transpose a List of Lists

(params = list(trn = list(col = "red",   lwd = 1,   lty = 2),
               tst = list(col = "green", lwd = 1.5, lty = 1)))
$trn
$trn$col
[1] "red"

$trn$lwd
[1] 1

$trn$lty
[1] 2


$tst
$tst$col
[1] "green"

$tst$lwd
[1] 1.5

$tst$lty
[1] 1
pm becomes a strange object, which is a list with a dimension attribute
    trn   tst    
col "red" "green"
lwd 1     1.5    
lty 2     1
(params_t = sapply(rownames(pm), function(r) unlist(pm[r, ]), simplify = FALSE))
#             |      |                         +-- convert a list to a vector
#             |      +-- c("col", "lwd", "lty")
#             +-- use sapply(simplify = FALSE) instead of lapply() to use USE.NAMES feature
$col
    trn     tst 
  "red" "green" 

$lwd
trn tst 
1.0 1.5 

$lty
trn tst 
  2   1