Flatten recursive list

前端 未结 4 1179
无人共我
无人共我 2021-02-14 09:33

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

4条回答
  •  生来不讨喜
    2021-02-14 10:05

    rlang::squash is pretty magical:

    set.seed(47)
    
    d = list(list(list(iris[sample(1:150,3),],
                       iris[sample(1:150,3),]),
                  list(list(iris[sample(1:150,3),],
                            list(iris[sample(1:150,3),],
                                 iris[sample(1:150,3),])
                  ))
    ))
    
    rlang::squash(d)
    #> [[1]]
    #>     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
    #> 147          6.3         2.5          5.0         1.9  virginica
    #> 56           5.7         2.8          4.5         1.3 versicolor
    #> 113          6.8         3.0          5.5         2.1  virginica
    #> 
    #> [[2]]
    #>     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
    #> 124          6.3         2.7          4.9         1.8  virginica
    #> 86           6.0         3.4          4.5         1.6 versicolor
    #> 103          7.1         3.0          5.9         2.1  virginica
    #> 
    #> [[3]]
    #>    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
    #> 59          6.6         2.9          4.6         1.3 versicolor
    #> 70          5.6         2.5          3.9         1.1 versicolor
    #> 81          5.5         2.4          3.8         1.1 versicolor
    #> 
    #> [[4]]
    #>     Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
    #> 139          6.0         3.0          4.8         1.8 virginica
    #> 21           5.4         3.4          1.7         0.2    setosa
    #> 104          6.3         2.9          5.6         1.8 virginica
    #> 
    #> [[5]]
    #>    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
    #> 25          4.8         3.4          1.9         0.2     setosa
    #> 90          5.5         2.5          4.0         1.3 versicolor
    #> 75          6.4         2.9          4.3         1.3 versicolor
    

提交回复
热议问题