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

前端 未结 3 1001
轮回少年
轮回少年 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:42

    Here are some ideas using functions from purrr. Thanks for the great suggestions from @cderv.

    Here is the first one. The use of pluck is similar to $.

    list %>% flatten() %>% transpose() %>% pluck("t")
    $a
    [1] 1
    
    $b
    [1] 2
    
    $a
    [1] 3
    
    $b
    [1] 4
    

    Here is the second one.

    list %>% flatten() %>% map("t") 
    $a
    [1] 1
    
    $b
    [1] 2
    
    $a
    [1] 3
    
    $b
    [1] 4
    

    Finally, if we want a vector, we can use map_dbl if we know the elements in t are all numeric.

    list %>% flatten() %>% map_dbl("t")
    a b a b 
    1 2 3 4
    

提交回复
热议问题