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...
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).
Flatten the list to "remove the brackets" using a nested list comprehension. This will un-nest each list stored in your list of lists!
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.
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.
I think this does the trick
new.pp <- unlist(pp,recursive=FALSE)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With