Julien Navarre Julien Navarre - 1 month ago 12
R Question

How can I recursively access named elements of sub lists?

I have a nested list, I would like to get the "x" element of each sub list. What is the easiest way to do that ?

my.list <- list(a = list(x = 1, y = 1),
b = list(x = 2, y = 2),
c = list(x = 3, y = 3))


I'm actualy doing it using an anonymous function in
lapply
:

lapply(my.list, function(x) x$x)


But why this doesn't work ? And what should I change to make it work ?

lapply(my.list, `$`, name = `x`)


Thank you.

Answer

We can try

sapply(my.list, `[[`, "x")
# a b c 
#1 2 3