Miski123
Miski123

Reputation: 135

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

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

Answers (4)

akrun
akrun

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

ThomasIsCoding
ThomasIsCoding

Reputation: 101034

Maybe the code below works only for your specific example

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

Upvotes: 1

Onyambu
Onyambu

Reputation: 79188

also:

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

Upvotes: 2

Mohanasundaram
Mohanasundaram

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

Related Questions