Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

What you got with rep(list(c(1, 2)), 4) is not a list of lists; it's a list of numeric vectors. If you really want a list of lists, try

replicate(4,list(1,2),simplify=FALSE)

or

rep(list(list(1, 2)), 4)

You can understand a little bit better why this works as it does by performing exegesis on the first line of ?rep:

‘rep’ replicates the values in ‘x’.

In other words, it promises to replicate the contents of x, but not necessarily to replicate x itself. (This is why the second suggestion, kindly contributed by @flodel, works -- it makes x into a list whose contents are a list -- and why the vector-based rep() works -- the contents of the list are a vector.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top