Home > OS >  Select the first element from the first list, the second element from the second list, and so on, in
Select the first element from the first list, the second element from the second list, and so on, in

Time:05-17

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?

CodePudding user response:

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]])

CodePudding user response:

also:

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