# Extract matrix rows from list

I have a list of matrices (actually a list column in a larger dataframe) from which I want to extract particular rows or columns. Given a simple list like this:

``````l <- list(
matrix(1:4, nrow = 2),
matrix(5:8, nrow = 2),
matrix(9:12, nrow = 2),
matrix(13:16, nrow = 2)
)
``````

It's easy to get a single row by indexing like this:

``````> l[][1,]
 5 7
``````

But how can I extract the nth row from every item in the list at once? Something like:

``````> l[[]][1,]
 1 3
 5 7
 9 11
 13 15
``````

I have a feeling I want to use `purrr::map` here somehow, but I can't quite wrap my head around how. Any hints?

Is this something you can work with?

``````library(purrr)
> l_f <- flatten(l)
> l_f
[]
 1

[]
 2

[]
 3

[]
 4

[]
 5

[]
 6

[]
 7

[]
 8

[]
 9

[]
 10

[]
 11

[]
 12

[]
 13

[]
 14

[]
 15

[]
 16
``````

Yes you can use `purrr`. `map` will allow you to iterate on each element of the list, so your matrix, on which you can apply the function you want.

``````l <- list(
matrix(1:4, nrow = 2),
matrix(5:8, nrow = 2),
matrix(9:12, nrow = 2),
matrix(13:16, nrow = 2)
)

library(purrr)

# using purrr style function
l %>%
map(~.x[1, ])
#> []
#>  1 3
#>
#> []
#>  5 7
#>
#> []
#>   9 11
#>
#> []
#>  13 15
``````

Created on 2018-12-06 by the reprex package (v0.2.1)

2 Likes

I think that does exactly what I need, thanks!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.