Flatten deeply nested list of dataframes
Asked Answered
R

2

5

Consider this nested list of dataframes:

df <- data.frame(x = 1:5, y = letters[1:5])
l <- list(df, list(df, df), list(df, list(df, df, list(df))), list(df), df)

How can one get from this deeply nested list to a simple list of dataframes:

list(df, df, df, df, df, df, df, df, df)

Usual solutions (like here) fails to keep dataframes' structure.

Reneerenegade answered 22/4, 2022 at 14:2 Comment(0)
A
6

A convenient option is to use rrapply:

rrapply::rrapply(l, classes = "data.frame", how = "flatten")

Check whether it's the same as the desired output:

identical(list(df, df, df, df, df, df, df, df, df), 
          rrapply(l, classes = "data.frame", how = "flatten"))

[1] TRUE
Adala answered 22/4, 2022 at 14:12 Comment(1)
I was not aware of rrapply's classes argument, thanks!Schlesinger
F
2

Or using a base R recursive function:

unnestdf <- function(x) 
{
  if (is.data.frame(x))
    return(list(x))
  if (!is.list(x))
    return(NULL)
  unlist(lapply(x, unnestdf), F)
}

unnestdf(l)

#> [[1]]
#>   x y
#> 1 1 a
#> 2 2 b
#> 3 3 c
#> 4 4 d
#> 5 5 e
#> 
#> [[2]]
#>   x y
#> 1 1 a
#> 2 2 b
#> 3 3 c
#> 4 4 d
#> 5 5 e
#> 
#> [[3]]
#>   x y
#> 1 1 a
#> 2 2 b
#> 3 3 c
#> 4 4 d
#> 5 5 e
#> 
#> [[4]]
#>   x y
#> 1 1 a
#> 2 2 b
#> 3 3 c
#> 4 4 d
#> 5 5 e
#> 
#> [[5]]
#>   x y
#> 1 1 a
#> 2 2 b
#> 3 3 c
#> 4 4 d
#> 5 5 e
#> 
#> [[6]]
#>   x y
#> 1 1 a
#> 2 2 b
#> 3 3 c
#> 4 4 d
#> 5 5 e
#> 
#> [[7]]
#>   x y
#> 1 1 a
#> 2 2 b
#> 3 3 c
#> 4 4 d
#> 5 5 e
#> 
#> [[8]]
#>   x y
#> 1 1 a
#> 2 2 b
#> 3 3 c
#> 4 4 d
#> 5 5 e
#> 
#> [[9]]
#>   x y
#> 1 1 a
#> 2 2 b
#> 3 3 c
#> 4 4 d
#> 5 5 e
Figueroa answered 22/4, 2022 at 15:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.