There are quite a few questions apparently on this topic, but I can\'t see any general solution proposed: I have a deeply recursive list and want to flatten it into a single lis
This is a general flatten function using only base R:
flatten <- function(x) {
if (!inherits(x, "list")) return(list(x))
else return(unlist(c(lapply(x, flatten)), recursive = FALSE))
}
Result:
flatten(d)
#[[1]]
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#44 5.0 3.5 1.6 0.6 setosa
#138 6.4 3.1 5.5 1.8 virginica
#87 6.7 3.1 4.7 1.5 versicolor
#
#[[2]]
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#19 5.7 3.8 1.7 0.3 setosa
#1 5.1 3.5 1.4 0.2 setosa
#71 5.9 3.2 4.8 1.8 versicolor
#
#[[3]]
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#31 4.8 3.1 1.6 0.2 setosa
#98 6.2 2.9 4.3 1.3 versicolor
#134 6.3 2.8 5.1 1.5 virginica
#
#[[4]]
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#140 6.9 3.1 5.4 2.1 virginica
#119 7.7 2.6 6.9 2.3 virginica
#57 6.3 3.3 4.7 1.6 versicolor
#
#[[5]]
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#73 6.3 2.5 4.9 1.5 versicolor
#54 5.5 2.3 4.0 1.3 versicolor
#146 6.7 3.0 5.2 2.3 virginica
Similarly:
x <- list(list("A"), list(list("A"), list("A")))
flatten(x)
#[[1]]
#[1] "A"
#
#[[2]]
#[1] "A"
#
#[[3]]
#[1] "A"
x <- list(list(1), list(list(2), list(3)))
flatten(x)
#[[1]]
#[1] 1
#
#[[2]]
#[1] 2
#
#[[3]]
#[1] 3
It seems a bit round-about to add more lists when the goal is to remove them, but the list
/unlist
route is the only reliable way to concatenate lists with different numbers of elements.