我正在尝试提取嵌套列表的最后一个元素。我怎样才能做到这一点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"
Run Code Online (Sandbox Code Playgroud)
由reprex 包于 2021 年 5 月 21 日创建(v2.0.0)
简单地使用purrr::pluck:
library(purrr)
map(x, ~ pluck(.x, length(.x)))
Run Code Online (Sandbox Code Playgroud)
或者更容易使用dplyr::last:
library(purrr)
library(dplyr)
map(x, last)
Run Code Online (Sandbox Code Playgroud)
在 base 中R,反转每个列表元素并获取第一项:
lapply(x, function(y) rev(y)[[1]])
lapply(x, \(y) rev(y)[[1]]) # R >= 4.1.0
Run Code Online (Sandbox Code Playgroud)
或者
mapply(`[[`, x, sapply(x, length), SIMPLIFY = F)
Run Code Online (Sandbox Code Playgroud)
如果删除参数,它将返回单个向量,SIMPLIFY = F因为默认值为TRUE。
这是通过迭代列表x和并行的输出并将其应用于作为提取运算符的sapply(x, length)函数来实现的。`[[`