Hi folks, I would appreciate help about subsetting and flattening lists using purrr. Bellow is an example including a for loop which does the job and my attempt to do the same using purrr.
library(tidyverse)
library(reprex)
l <-
list(
name1 = list(
mat = matrix(1:9, 3),
chr = "some text"
),
name2 = list(
mat = matrix(11:19, 3),
chr = "some othet text"
)
)
l
#> $name1
#> $name1$mat
#> [,1] [,2] [,3]
#> [1,] 1 4 7
#> [2,] 2 5 8
#> [3,] 3 6 9
#>
#> $name1$chr
#> [1] "some text"
#>
#>
#> $name2
#> $name2$mat
#> [,1] [,2] [,3]
#> [1,] 11 14 17
#> [2,] 12 15 18
#> [3,] 13 16 19
#>
#> $name2$chr
#> [1] "some othet text"
# here a for loop which produces desired output, that is subset only matrix and flatten it while keeping the top level names:
desired_l <- list()
for (i in names(l)) {
desired_l[[i]] <- l[[i]][["mat"]]
}
desired_l
#> $name1
#> [,1] [,2] [,3]
#> [1,] 1 4 7
#> [2,] 2 5 8
#> [3,] 3 6 9
#>
#> $name2
#> [,1] [,2] [,3]
#> [1,] 11 14 17
#> [2,] 12 15 18
#> [3,] 13 16 19
# here my attempt to achieve the same using purrr
## function for subsetting the list (didnt know how to use purrr::keep())
SubList <- function(l, keep_name) {
l[keep_name]
}
sub_l <- map(l, SubList, keep_name = "mat")
flatt_l <- flatten(sub_l)
flatt_l
#> $mat
#> [,1] [,2] [,3]
#> [1,] 1 4 7
#> [2,] 2 5 8
#> [3,] 3 6 9
#>
#> $mat
#> [,1] [,2] [,3]
#> [1,] 11 14 17
#> [2,] 12 15 18
#> [3,] 13 16 19
# It is pretty close but I dont know how to go about the names. flatten() pulls the names from the level bellow, but I would like to keep top-level names as in output from for loop.
Thank you a lot for help!
Regards,
Amel
Created on 2023-01-16 by the reprex package (v2.0.1)