使用purrr和map遍历列表的更深层次?

时间:2019-11-18 03:41:22

标签: r purrr

我正在尝试查看如何从嵌套列表的第n级提取值。例如...如果这些都在第二层,我可以像这样使用map()

> testlist1 <- 
+   list(
+     list('veggie' = 'apple', 'food' = 'bacon'),
+     list('veggie' = 'banana', 'food' = 'burger'),
+     list('veggie' = 'tomato', 'food' = 'sausage'),
+     list('veggie' = 'pickle', 'food' = 'chicken'),
+     list('veggie' = 'chestnut', 'food' = 'salmon'),
+     list('veggie' = 'seaweed', 'food' = 'tuna')
+   )
> 
> testlist1 %>% map('veggie')
[[1]]
[1] "apple"

[[2]]
[1] "banana"

[[3]]
[1] "tomato"

[[4]]
[1] "pickle"

[[5]]
[1] "chestnut"

[[6]]
[1] "seaweed"

但是,当它们深入时,我想必须有某种map()循环到图层的方法了吗?示例:

testlist2 <- list(
  list(
    list(
      list('veggie' = 'apple', 'food' = 'bacon')
    ), 
    list(
      list('veggie' = 'banana', 'food' = 'burger')
    )
  ),
  list(
    list(
      list('veggie' = 'tomato', 'food' = 'sausage')
    ), 
    list(
      list('veggie' = 'pickle', 'food' = 'chicken')
    )
  ),
  list(
    list(
      list('veggie' = 'chestnut', 'food' = 'salmon')
    ), 
    list(
      list('veggie' = 'seaweed', 'food' = 'tuna')
    )
  )
)

2 个答案:

答案 0 :(得分:1)

如何取消列出数据并选择具有所需名称的元素?

temp <- unlist(testlist2)
unname(temp[names(temp) == "veggie"])
#[1] "apple"    "banana"   "tomato"   "pickle"   "chestnut" "seaweed" 

即使数据深度很深,这也将起作用。

答案 1 :(得分:1)

按照@MrFlick的建议,map_depth在这里可以提供帮助

library(tidyverse)

testlist2 <- list(
  list(
    list(
      list('veggie' = 'apple', 'food' = 'bacon')
    ), 
    list(
      list('veggie' = 'banana', 'food' = 'burger')
    )
  ),
  list(
    list(
      list('veggie' = 'tomato', 'food' = 'sausage')
    ), 
    list(
      list('veggie' = 'pickle', 'food' = 'chicken')
    )
  ),
  list(
    list(
      list('veggie' = 'chestnut', 'food' = 'salmon')
    ), 
    list(
      list('veggie' = 'seaweed', 'food' = 'tuna')
    )
  )
)

使用第一个参数设置所需的列表深度

testlist2 %>% map_depth(3, 'veggie')
#> [[1]]
#> [[1]][[1]]
#> [[1]][[1]][[1]]
#> [1] "apple"
#> 
#> 
#> [[1]][[2]]
#> [[1]][[2]][[1]]
#> [1] "banana"
#> 
#> 
#> 
#> [[2]]
#> [[2]][[1]]
#> [[2]][[1]][[1]]
#> [1] "tomato"
#> 
#> 
#> [[2]][[2]]
#> [[2]][[2]][[1]]
#> [1] "pickle"
#> 
#> 
#> 
#> [[3]]
#> [[3]][[1]]
#> [[3]][[1]][[1]]
#> [1] "chestnut"
#> 
#> 
#> [[3]][[2]]
#> [[3]][[2]][[1]]
#> [1] "seaweed"

或使用负数从最低级别开始计数

testlist2 %>% map_depth(-2, 'veggie')
#> [[1]]
#> [[1]][[1]]
#> [[1]][[1]][[1]]
#> [1] "apple"
#> 
#> 
#> [[1]][[2]]
#> [[1]][[2]][[1]]
#> [1] "banana"
#> 
#> 
#> 
#> [[2]]
#> [[2]][[1]]
#> [[2]][[1]][[1]]
#> [1] "tomato"
#> 
#> 
#> [[2]][[2]]
#> [[2]][[2]][[1]]
#> [1] "pickle"
#> 
#> 
#> 
#> [[3]]
#> [[3]][[1]]
#> [[3]][[1]][[1]]
#> [1] "chestnut"
#> 
#> 
#> [[3]][[2]]
#> [[3]][[2]][[1]]
#> [1] "seaweed"

Created on 2019-11-18 by the reprex package (v0.3.0)