Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

list

r

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

like image 263
h.l.m Avatar asked Jun 18 '13 09:06

h.l.m


People also ask

How do I remove a list from inside list?

We can remove a list inside a list same way like we remove the single list, just provide the reference of the list object to the del function. del(list_object).

How do I remove a nested list from a list in Python?

Flatten the list to "remove the brackets" using a nested list comprehension. This will un-nest each list stored in your list of lists!

Can you remove a list from a list Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.

How do you flatten a nested list in Python?

Provide two arguments to the sum() method: my_list and an empty list (i.e. [ ] ). sum() combines my_list and [ ] to produce a flattened list.


1 Answers

I think this does the trick

new.pp <- unlist(pp,recursive=FALSE) 
like image 168
Geoffrey Absalom Avatar answered Sep 20 '22 14:09

Geoffrey Absalom