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

Extract specific list elements from a nested list in R?

I have a nested list that looks like this:

x <- list(list(a = c(1,10), b=c(2,10)), list(c=c(3,10), d=c(6,10)), list(e= c(3,10)))
> x
[[1]]
[[1]]$a
[1]  1 10

[[1]]$b
[1]  2 10


[[2]]
[[2]]$c
[1]  3 10

[[2]]$d
[1]  6 10


[[3]]
[[3]]$e
[1]  3 10

I’m trying to extract just the first value from each list element. However, if the length of a list is greater than 1, then I want to add the extracted values together.

For example, in my list x above, we can see that the first list (i.e., x[[1]]) contains a and b… so I want to extract the 1st values from this list (in this case, 1 and 2) and since they belong to the same list, they get added together.

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

At the end, Im just trying to return a vector of the extracted (and where necessary, added) values. So in my example, I would expect a vector like: [1] 3 9 3.

>Solution :

Using nested sapply

sapply(x, function(y) sum(sapply(y, head, 1)))
#[1] 3 9 3

Or combine each list into a matrix and take sum of first column/row.

sapply(x, function(y) sum(do.call(rbind, y)[, 1]))
#sapply(x, function(y) sum(do.call(cbind, y)[1, ]))
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