I am trying to extract the last element of nested lists. How can I do this with purrr
? In the example below the results should be all the elements with the value "c".
I have seen this, but I am particularly interested in a solution with purrr.
Many thanks
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"
Created on 2021-05-21 by the reprex package (v2.0.0)
Using
purrr::pluck
simply:Or even easier use
dplyr::last
:In just base
R
, reverse each list element and take the first item:Or
Which would return a single vector if remove the argument
SIMPLIFY = F
because the default isTRUE
.This works by iterating through your list
x
and the output ofsapply(x, length)
in parallel and applying it to the function`[[`
which is an extraction operator.