考虑一下这个嵌套的数据格式列表:
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)
如何从这个深嵌套的列表中获得一个简单的数据格式列表:
list(df, df, df, df, df, df, df, df, df)
通常的解决方案(如here)无法保持dataframes的结构。
发布于 2022-04-22 14:12:32
一个方便的选择是使用rrapply
rrapply::rrapply(l, classes = "data.frame", how = "flatten")
检查它是否与所需的输出相同:
identical(list(df, df, df, df, df, df, df, df, df),
rrapply(l, classes = "data.frame", how = "flatten"))
[1] TRUE
发布于 2022-04-22 15:17:40
或者使用基本的R递归函数:
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
https://stackoverflow.com/questions/71970037
复制相似问题