Search code examples
rlistdataframeapplycbind

Combine different elements of a list in a dataframe using apply


I do have a main List containing sub-lists also containing elements. I would like to make a dataframe by combining the eighth element of each sub-list from the main List.

If I write this manually that's working:

DF <- cbind(List[[1]][[8]],List[[2]][[8]], ... List[[n]][[8]])

That's working, the result is the wanted dataframe. But I have a lot of sub-list within the main list and the lenght of the main List is not always the same. So, it is not efficient to write it manually.

I try this :

DF <- lapply(1:length(List), function(i) cbind(List[[i]][[8]]))

But the result is a list of lenght(List) containing indeed the eighth element of each sub-list but not the wanted dataframe. How can a obtain a dataframe and not another list ?


Solution

  • Try this

    do.call(rbind.data.frame, lapply(1:length(List), function(i) cbind(List[[i]][[8]])))