How to select multiple lists elements at once by pluck?

If the list is in a balanced manner:

mm <- list(a = list(1:2), b = list(3:4), d = list(5:6))
nn <- list(a = list(7:8), b = list(9:10), d = list(11:12))
kk <- list(mm, nn)

kk |> map(pluck(2))
[[1]]
[[1]][[1]]
[1] 3 4

[[2]]
[[2]][[1]]
[1] 9 10

If we want to pluck arbitrary list element 2, 3 or more at once with map, like pluck(2:n) didn't work,

or paste("pluck(., ", seq(2:n), ")", collapse = ", ", sep = "") didn't work too,

or paste("pluck(., ", c(2, 3, 5, n), ")", collapse = ", ", sep = "") didn't work too,

how can we do?

We hope the outputs like this

#> List of 2
#>  $ :List of 2
#>   ..$ : int [1:2] 3 4
#>   ..$ : int [1:2] 5 6
#>  $ :List of 2
#>   ..$ : int [1:2] 9 10
#>   ..$ : int [1:2] 11 12
......

Or any other solutions?

Thanks!

E.g. with

library(purrr)

mm <- list(a = list(1:2), b = list(3:4), d = list(5:6))
nn <- list(a = list(7:8), b = list(9:10), d = list(11:12))
kk <- list(mm, nn)

kk1 <- kk |> purrr::map(~c(pluck(.,2),pluck(.,3))) 
str(kk1)
#> List of 2
#>  $ :List of 2
#>   ..$ : int [1:2] 3 4
#>   ..$ : int [1:2] 5 6
#>  $ :List of 2
#>   ..$ : int [1:2] 9 10
#>   ..$ : int [1:2] 11 12
Created on 2021-09-15 by the reprex package (v2.0.0)

?

1 Like

When use paste in the map with purrr expression, it didn't work

mm <- list(a = list(1:2), b = list(3:4), d = list(5:6))
nn <- list(a = list(7:8), b = list(9:10), d = list(11:12))
kk <- list(mm, nn)

kk |> purrr::map(~c(paste("pluck(., ", seq(2:3), ")", collapse = ", ", sep = "")))

How to figure it out?

It works for me but I agree that the output is not very interesting.
Please show us the desired output, because you did not mention that before.

We modified needs clearly at the top post,thanks to your suggestion.