Apostolos Polymeros
Apostolos Polymeros

Reputation: 843

R: list containing lists

I would like to ask if anybody can find what is the mistake in the 2nd construction for not receiving the same list as in the 1st construction. Is there a way to refer to the name of an element of a list ? For example, somefunction(myList[[1]])==a1 ?

# construction #1
myList <- list(a1 = list(a2 = list("a21", "a22")), b1 = list("b1", "b2"))

# construction #2
myList                  <- list()
myList[[1]]             <- list(a1=list())
myList[[1]][[1]]        <- list(a2=list())
myList[[1]][[1]][[1]]   <- "a21"
myList[[1]][[1]][[2]]   <- "a22"
myList[[2]]             <- list(b1=list())
myList[[2]][[1]]        <- "b1"
myList[[2]][[2]]        <- "b2"

Thank you very much in advance

Upvotes: 2

Views: 7759

Answers (1)

Ari B. Friedman
Ari B. Friedman

Reputation: 72731

Let's make this simpler and look just at the first line:

myList <- list(a1 = "anything")
# vs
myList <- list()
myList[[1]] <- list(a1="anything")

In the first construction, slot 1 of the top list is named "a1" and contains "anything". In the second construction, slot 1 of the top list is named nothing and contains a list whose first slot is named "a1" and contains "anything".

To make them similar, try:

myList <- list()
myList[["a1"]] <- "anything"

Upvotes: 5

Related Questions