Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

r - 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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think this does the trick

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...