Skip to contents

Recursively flattens any nested lists into a single-level list. Non-list objects are treated as leaves and kept as single elements. If preserve_df = TRUE, data.frames are treated as leaves and not exploded.

Usage

list_flatten2(x, preserve_df = TRUE, keep_names = TRUE)

Arguments

x

(list)
A possibly nested list that should be flattened.

preserve_df

(Scalar logical)
If TRUE (default), data.frames are treated as leaves and not flattened inside.

keep_names

(Scalar logical)
If TRUE (default), names of leaf elements are retained.

Value

A single-level list containing all leaf elements from x, in left-to-right order.

Examples

#----------------------------------------------------------------------------
# list_flatten2() examples
#----------------------------------------------------------------------------
library(bkbase)

# Flatten
x <- list(1, list(2, list(3, 4)), 5)
list_flatten2(x)
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] 2
#> 
#> [[3]]
#> [1] 3
#> 
#> [[4]]
#> [1] 4
#> 
#> [[5]]
#> [1] 5
#> 

# Preserves leaf names and data frames as leaves
y <- list(list(a = 1:2), data.frame(x = 1:2), list(b = "z"))
list_flatten2(y)
#> $a
#> [1] 1 2
#> 
#> [[2]]
#>   x
#> 1 1
#> 2 2
#> 
#> $b
#> [1] "z"
#> 

# Drop leaf names
z <- list(list(a = c("name1" = 1, "name2" = 2)), list(b = "z"))
list_flatten2(z, keep_names = FALSE)
#> [[1]]
#> name1 name2 
#>     1     2 
#> 
#> [[2]]
#> [1] "z"
#>