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

╄→尐↘猪︶ㄣ 提交于 2020-03-17 12:00:12

问题


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))) 

How to select all "t" values with purrr?


回答1:


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.




回答2:


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



回答3:


With purrr::map

map(list, ~map(.x, ~.x$t))

Output is still list of list

$node
$node$a
[1] 1

$node$b
[1] 2


$node
$node$a
[1] 3

$node$b
[1] 4

unlist

To convert to vector

unlist(map(list, ~map(.x, ~.x$t)))

Output

node.a node.b node.a node.b 
     1      2      3      4     


来源:https://stackoverflow.com/questions/46123987/how-to-select-elements-with-the-same-name-from-nested-list-with-purrr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!