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

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?

+4
source share
3 answers

You can use modify_depththis if you know at what level you want to extract information.

You want to output tfor 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 family of functions modifyreturns an object of the same type as the input, so you need to unlistget a vector instead of a list.

+3
source

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

. pluck $.

list %>% flatten() %>% transpose() %>% pluck("t")
$a
[1] 1

$b
[1] 2

$a
[1] 3

$b
[1] 4

.

list %>% flatten() %>% map("t") 
$a
[1] 1

$b
[1] 2

$a
[1] 3

$b
[1] 4

, , map_dbl, , t .

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

WITH purrr::map

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

The output is still a 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     
+1
source

Source: https://habr.com/ru/post/1685328/


All Articles