When I started to preinitialize lists of list in R which should be filled afterwards I wondered about the behaviour of list objects when used as value in rep(). When I am trying the following...
listOfLists <- rep(list(1, 2), 4)
... listOfLists is a single list:
1 2 1 2 1 2 1 2
However, I would assume it to be a list of lists which finally contain the values 1 and 2 each:
1 2
1 2
1 2
1 2
To get the desired result I have to surround the value entries with c() additionally:
listOfLists <- rep(list(c(1, 2)), 4)
I wonder why this is the case in R. Shouldn't list create a fully functional list as it normally does instead of doing something similar to c()? Why does grouping the values with c() actually solves the problem here?
Thank you for your thoughts!
Conclusion: Both Ben Bolker's and Peyton's posts give the final answer. It was the behaviour of neither the list()- nor the c()-function. Instead rep() seems to combine the entries of lists and vectors to one. Surrounding the values with another container makes rep() actualy "ignore" the first but repeat the second container.
It does create a fully functional list. The difference is that in your first example, you create a list with two elements, whereas in the second example, you create a list with one element--a vector.
When you combine lists (e.g., with rep
), you're essentially creating a new list with all the elements of the previous lists. In the first example, then, you'll have eight elements, and in the second example, you'll have four.
Another way to see this:
> length(list(1, 2))
[1] 2
> c(list(1, 2), list(1, 2), list(1, 2))
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 1
[[4]]
[1] 2
[[5]]
[1] 1
[[6]]
[1] 2
> length(list(1:2))
[1] 1
> c(list(1:2), list(1:2), list(1:2))
[[1]]
[1] 1 2
[[2]]
[1] 1 2
[[3]]
[1] 1 2