nouse
nouse

Reputation: 3461

Converting specific parts of lists to a dataframe

I have a large list of 2 elements containing lists of species containing lists of 25 vectors, resembling a set like this:

l1 <- list(time=runif(100), space=runif(100))
l2 <- list(time=runif(100), space=runif(100))

list1 <- list(test1=list(species1=l1, species2=l2),test2=list(species1=l1, species2=l2))

I think, its essentially a list of a list of lists.of vectors.

I want to create a data.frame from all space-vectors of all 'species' in just one of the two sublists:

final <- as.data.frame(cbind(unlist(list1[[2]]$species1$space), unlist(list1[[2]]$species2$space)))
names(final) <- names(list1[[2]])

Essentially, i need a loop/apply command that navigates me through list1[[2]]$species and picks all vectors called space.

Thank you very much!

Upvotes: 2

Views: 40

Answers (1)

akrun
akrun

Reputation: 886938

We can use a nested loop to extract the 'space' elements

data.frame(lapply(list1, function(x) 
          sapply(x, "[", 'space')))

Upvotes: 1

Related Questions