How to select elements with the same name from nested list with purrr?

前端 未结 3 993
轮回少年
轮回少年 2021-02-09 23:50
require(purrr)

list <- list( 
  node = list(a = list(y = 1, t = 1), b = list(y = 1, t = 2)),
  node = list(a = list(y = 1, t = 3), b = list(y = 1, t = 4))) 
<         


        
3条回答
  •  执念已碎
    2021-02-10 00:37

    You can use modify_depth for this if you know what level you want to pull the information out of.

    You want to pull t out for the nested lists, which is level 2.

    modify_depth(list, 2, "t")
    
    $node
    $node$a
    [1] 1
    
    $node$b
    [1] 2
    
    
    $node
    $node$a
    [1] 3
    
    $node$b
    [1] 4
    

    The purrr modify family of functions returns an object of the same type as the input, so you'd need to unlist to get a vector instead of a list.

提交回复
热议问题