我正在尝试提取嵌套列表的最后一个元素。我怎样才能做到这一点purrr
?在下面的示例中,结果应该是值为“c”的所有元素。我见过这个,但我对 purrr 的解决方案特别感兴趣。
非常感谢
x <- list(list(1,2,"c"), list(3,"c"), list("c"))
x
#> [[1]]
#> [[1]][[1]]
#> [1] 1
#>
#> [[1]][[2]]
#> [1] 2
#>
#> [[1]][[3]]
#> [1] "c"
#>
#>
#> [[2]]
#> [[2]][[1]]
#> [1] 3
#>
#> [[2]][[2]]
#> [1] "c"
#>
#>
#> [[3]]
#> [[3]][[1]]
#> [1] "c"
map(x, purrr::pluck, tail)
#> Error in map(x, purrr::pluck, tail): could not find function "map"
map(x, purrr::pluck, length(x))
#> Error in map(x, purrr::pluck, length(x)): could not find function "map"
purrr::pluck
简单地使用:
library(purrr)
map(x, ~ pluck(.x, length(.x)))
或者更容易使用dplyr::last
:
library(purrr)
library(dplyr)
map(x, last)
在 base 中R
,反转每个列表元素并取第一项:
lapply(x, function(y) rev(y)[[1]])
lapply(x, \(y) rev(y)[[1]]) # R >= 4.1.0
或者
mapply(`[[`, x, sapply(x, length), SIMPLIFY = F)
如果删除参数,它将返回单个向量,SIMPLIFY = F
因为默认值为TRUE
.
这是通过迭代您的列表x
和sapply(x, length)
并行输出并将其应用于`[[`
作为提取运算符的函数来工作的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句