Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a multiple-dim list like this DATA<-list(list(list(),list(),list()),list(list(),list(),list()),list(list(),list(),list()))?

Tags:

r

I want to pre-define a list like this using R

DATA<-list(
 list(list(),list(),list()),
 list(list(),list(),list()),
 list(list(),list(),list())
)

how to write it more concise? What if I want create a very huge Recursive list? This seems like a little easy, but I've been thinking a lot...

like image 491
freshlj Avatar asked Dec 06 '25 10:12

freshlj


2 Answers

You can use replicate() here.

DATA <- replicate(3, replicate(3, list(), simplify = FALSE), simplify = FALSE)

We replicate a list three times and then replicate that three times.

like image 82
MrFlick Avatar answered Dec 08 '25 22:12

MrFlick


You can try define a custom function nestLst with Reduce to create the nested list, e.g.,

nestLst <- function(dims) {
  Reduce(
    function(x, n) replicate(n, x, simplify = FALSE),
    append(list(list()), as.list(rev(dims)))
  )
}

where you only need to pass the dimensions of the desired nested list to the function.


Example

> nestLst(dims = c(2,3,2))
[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
list()

[[1]][[1]][[2]]
list()


[[1]][[2]]
[[1]][[2]][[1]]
list()

[[1]][[2]][[2]]
list()


[[1]][[3]]
[[1]][[3]][[1]]
list()

[[1]][[3]][[2]]
list()



[[2]]
[[2]][[1]]
[[2]][[1]][[1]]
list()

[[2]][[1]][[2]]
list()


[[2]][[2]]
[[2]][[2]][[1]]
list()

[[2]][[2]][[2]]
list()


[[2]][[3]]
[[2]][[3]][[1]]
list()

[[2]][[3]][[2]]
list()
like image 23
ThomasIsCoding Avatar answered Dec 08 '25 22:12

ThomasIsCoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!