如何使用dplyr / magrittr-R提取函数列表值的单个元素

时间:2018-06-23 14:11:48

标签: r dplyr purrr magrittr

我正在使用dplyr和管道以及NbClust函数编写代码,该函数返回名为All.indexAll.CriticalValuesBest.ncBest.partition

因此,我可以将表达式分配给某个变量,然后将Best.nc元素称为variable$Best.nc。但是如何使用管道提取Best.nc元素?

我尝试过purrr::map('[[', 'Best.nc'),但是没有用。

1 个答案:

答案 0 :(得分:3)

您可以直接使用基数R [[作为函数,而无需使用map

lst <- list(a = 1, b = 2)

lst %>% `[[`('a')
# [1] 1

variable %>% `[[`('Best.nc')

或者通过purrr,您可以使用pluck函数并仅提供元素索引或名称:

library(purrr)

lst %>% pluck('a')
# [1] 1
lst %>% pluck(1)
# [1] 1

针对您的情况:

variable %>% pluck('Best.nc')

pluck[[提取器的优点在于,您可以为嵌套列表进行深度索引,例如:

lst <- list(a = list(x = list(), y = 'm', z = 1:3), b = 2)

要访问嵌套在z中的a元素:

lst %>% pluck('a', 'z')
# [1] 1 2 3 
相关问题