Home > database >  Flatten deeply nested list of dataframes
Flatten deeply nested list of dataframes

Time:04-22

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.

CodePudding user response:

A convenient option is to use 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

CodePudding user response:

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
  • Related