简体   繁体   中英

How to remove a level of lists from a list of lists

I have created some lists within a list and would like to be able have each sublist element to be an individual element at the top level.

For example to create some dummy data:

pp <- lapply(10:15,function(y){
    lapply(10:20,function(z){
        as.data.frame(matrix(rnorm(z*y),nrow=z,ncol=y))
    })  
})

This creates the following output

> summary(pp)
     Length Class  Mode
[1,] 11     -none- list
[2,] 11     -none- list
[3,] 11     -none- list
[4,] 11     -none- list
[5,] 11     -none- list
[6,] 11     -none- list

where you can also do

> summary(pp[[1]])
      Length Class      Mode
 [1,] 10     data.frame list
 [2,] 10     data.frame list
 [3,] 10     data.frame list
 [4,] 10     data.frame list
 [5,] 10     data.frame list
 [6,] 10     data.frame list
 [7,] 10     data.frame list
 [8,] 10     data.frame list
 [9,] 10     data.frame list
[10,] 10     data.frame list
[11,] 10     data.frame list

The resultant output would just create a new list which has something like the below:

new.pp[[1]] <- pp[[1]][[1]]
new.pp[[2]] <- pp[[1]][[2]]

but was wondering if there was a smart or more efficient method of just removing one level of lists when you have lists within lists....

Ideally what I am looking for is some sort of function that carries this out for me, so that, if for example i had multiple levels of lists nested inside each other rather than just two, I can re-cursively use the function at each level bringing each element to the top of the list eventually...

我认为这可以解决问题

new.pp <- unlist(pp,recursive=FALSE)

Tidyverse approach:

library(purrr)
new.pp <- flatten(pp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM