I am creating a List with diferent elements
RR <- list(name="Miguel", salary=87000, union=T)
RR
$name
[1] "Miguel"
$salary
[1] 87000
$union
[1] TRUE
Getting elements by calling them by the name
RR$salary
[1] 87000
RR$name
[1] "Miguel"
RR$union
[1] TRUE
Getting the second element of the same list in 3 differnt ways
RR$salary
[1] 87000
RR[["salary"]]
[1] 87000
RR[[2]]
[1] 87000
Gettimg a list called TT with two elements
TT
$a
[1] "oot"
$b
[1] 55
adding a new elemetn to list TT
TT
$a
[1] "oot"
$b
[1] 55
$c
[1] "sailing"
Other ways to add elements
TT
$a
[1] "oot"
$b
[1] 55
$c
[1] "sailing"
[[4]]
[1] 38
[[5]]
[1] FALSE
[[6]]
[1] TRUE
[[7]]
[1] FALSE
Erasing an element of list TT
TT
$a
[1] "oot"
$c
[1] "sailing"
[[3]]
[1] 38
[[4]]
[1] FALSE
[[5]]
[1] TRUE
[[6]]
[1] FALSE
Connecting rwo list
c(list(name="Miguel", salary=87000, union=T),list(5))
$name
[1] "Miguel"
$salary
[1] 87000
$union
[1] TRUE
[[4]]
[1] 5
Getting the size og lists
length(RR)
[1] 3
length(TT)
[1] 6
Obtain the header by names and unlist them so i can obtain the values
names(RR)
[1] "name" "salary" "union"
ulj <- unlist(RR)
ulj
name salary union
"Miguel" "87000" "TRUE"
Getting the class
class(ulj)
[1] "character"
Crating a numeric list and getting the class
l <- list(a=5,b=58,c=77)
m <- unlist(l)
class(m)
[1] "numeric"
m
a b c
5 58 77
Chrateing a list with a numeric and a character value to see the class
n <- list(a=6,b="aacd")
no <- unlist(n)
class(no)
[1] "character"
no
a b
"6" "aacd"
Calling the specified function on each component of a list and returning another list
lapply(list(1:7,30:34),median)
[[1]]
[1] 4
[[2]]
[1] 32
Sapply() give us the desired matrix form in the output.
sapply(list(1:7,30:34),median)
[1] 4 32
Creating a list called PQ that has males femailes and I. the function lapply() gets rather which element is M which is F and which is I
PQ <- c("F","F","M","F","I","M","M")
lapply(c("M","F","I"),function(gender) which(PQ==gender))
Recursive Lists Lists can be recursive, meaning that you can have lists within lists.
ww <- list(u = 6, v = 34)
dd <- list(w = 35)
pl <- list(ww, dd)
pl
[[1]]
[[1]]$u
[1] 6
[[1]]$v
[1] 34
[[2]]
[[2]]$w
[1] 35
Size of pl
length(pl)
[1] 2
This code makes a into a two-component list, with each component itself also being a list. The concatenate function c() has an optional argument recursive, which controls whether flattening occurs when recursive lists are combined.
c(list(m=3,c=7,c=list(h=11,r=88)))
$m
[1] 3
$c
[1] 7
$c
$c$h
[1] 11
$c$r
[1] 88
with recursive set to TRUE, we got a single list as a result; only the names look recursive.
c(list(m=3,c=7,c=list(h=11,r=88)),recursive=T)
m c c.h c.r
3 7 11 88