Reputation: 135
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?
Upvotes: 2
Views: 452
Reputation: 886938
Use
library(purrr)
imap_dbl(lst, ~ pluck(.x, .y))
[1] 1 5 9
Or more compactly
imap_dbl(lst, pluck)
[1] 1 5 9
Upvotes: 1
Reputation: 101034
Maybe the code below works only for your specific example
> unlist(diag(do.call(cbind,lst)))
[1] 1 5 9
Upvotes: 1
Reputation: 2949
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]])
Upvotes: 4