Search code examples
rlistextract

How to extract values from a list with multiple levels in r


I have a list looks like this

[[1]]

[[1]][[1]]

[[1]][[1]]$p1est.z [1] 2.890829

[[1]][[1]]$p1se.z [1] 0.1418367

[[1]][[2]]

[[1]][[2]]$p2est.w [1] 4.947014

[[1]][[2]]$p2se.w [1] 0.5986682

[[2]]

[[2]][[1]]

[[2]][[1]]$p1est.z [1] 3.158164

[[2]][[1]]$p1se.z [1] 0.138770

[[2]][[2]]

[[2]][[2]]$p2est.w [1] 5.052874

[[2]][[2]]$p2se.w [1] 0.585608

How can I extract values of "p1est.z" from both levels? since I need to compute the average of them. Thanks!


Solution

  • Actually the unlist() function out of the box should probably work here:

    output <- unlist(your_list)
    output[names(output) == "p1est.z"]
    
     p1est.z  p1est.z 
    2.890829 3.158164 
    

    Data:

    your_list <- list(
                     list(list(p1est.z=2.890829, p1se.z=0.1418367),
                          list(p1est.w=4.947014, p2se.w=0.5986682)),
                     list(list(p1est.z=3.158164, p1se.z=0.138770),
                          list(p1est.w=5.052874, p2se.w=0.585608)))