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...
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With