ask about list, what does [[3]] mean?

> g <- "My First List"
> h <- c(25,26,18,39)
> j <- matrix(1:10, nrow=5)
> k <- c("one","two","three")
> mylist <- list(title=g, ages=h,j,k)
> mylist
$title
[1] "My First List"

$ages
[1] 25 26 18 39

[[3]]
     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10

[[4]]
[1] "one"   "two"   "three"

I don't understand [[3]] and [[4]] above. I think g is [[1]], then h,j,k are 2,3,4?

Yes. You named the first two elements of the list, so they are shown as title and ages. The remaining elements have no name, so they are labeled with their position in the list. The double bracket returns the nth element of the list.

mylist[[1]]

would return

[1] "My First List"

But where is ages[[2]]??? I only see ages[[1]] [[3]] [[4]]

mylist has four elements. The first one is named test and it contains a character vector with one element. The second is named ages and it contains a vector of four numbers. The third is unnamed and it contains a matrix or 10 elements. The fourth is unnamed and it contains a character vector of three elements.
Try this

mylist <- list(title=g, ages=h, third = j, fourth =  k)
mylist

you will see that [[3]] is replaced by $third and [[4]] is replaced by $fourth.

1 Like

Aha, I see. Very clear explanation! Thank you so much!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.