Select the first element from the first list, the second element from the second list, and so on, in a nested list

Viewed 69

Let's say I have a list like this:

lst <- list(list(1,2,3),list(4,5,6),list(7,8,9))

I would then like to extract the elements 1, 5, and 9. How should I do that in an efficient manner? I've come across this post; Select first element of nested list, where it is suggested that one should use:

lapply(x, '[[', 1)

to select the first element of a nested list. I was wondering if something similar could be done in the situation described above?

4 Answers

You can use the sapply using the length of the list and the function to subset the list as below:

sapply(1:length(lst), function(x) lst[[x]][[x]])

also:

mapply('[[', lst, seq_along(lst))
[1] 1 5 9

Use

library(purrr)
imap_dbl(lst, ~ pluck(.x, .y))
[1] 1 5 9

Or more compactly

imap_dbl(lst, pluck)
[1] 1 5 9

Maybe the code below works only for your specific example

> unlist(diag(do.call(cbind,lst)))
[1] 1 5 9
Related