Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading