2
list(list(NULL,NULL),list(NULL,NULL))

The result is:

[[1]]
[[1]][[1]]
NULL

[[1]][[2]]
NULL

[[2]]
[[2]][[1]]
NULL

[[2]][[2]]
NULL

Supposing I want to do this for larger numbers than 2, is there a way to get the same list structure with replicate?

Logister
  • 1,852
  • 23
  • 26

3 Answers3

4

Use replicate

replicate(n=3, {replicate(n=3,NULL,simplify=FALSE)},simplify=FALSE)


[[1]]
[[1]][[1]]
NULL

[[1]][[2]]
NULL

[[1]][[3]]
NULL


[[2]]
[[2]][[1]]
NULL

[[2]][[2]]
NULL

[[2]][[3]]
NULL


[[3]]
[[3]][[1]]
NULL

[[3]][[2]]
NULL

[[3]][[3]]
NULL

Or more simplly (thanks @RichardScriven)

replicate(3, list(replicate(3, list(NULL))))
mnel
  • 113,303
  • 27
  • 265
  • 254
4

You can do it with fewer letters using rep:

rep(list(rep(list(NULL), 3)), 3)


[[1]]
[[1]][[1]]
NULL

[[1]][[2]]
NULL

[[1]][[3]]
NULL


[[2]]
[[2]][[1]]
NULL

[[2]][[2]]
NULL

[[2]][[3]]
NULL


[[3]]
[[3]][[1]]
NULL

[[3]][[2]]
NULL

[[3]][[3]]
NULL
IRTFM
  • 258,963
  • 21
  • 364
  • 487
3

Maybe write a little function so that you can adjust the replications and the length of each list, and also have the option to return an array or a list.

nest <- function(len = 1L, n = 1L, ...) {
    replicate(n, vector("list", len), ...)
}
nest()
nest(2)
nest(2, simplify = FALSE)
nest(3, 2, simplify = FALSE)
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245