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[[2]][1,]
[1] 5 7

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

> l[[]][1,]
[1] 1 3
[2] 5 7
[3] 9 11
[4] 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]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

[[5]]
[1] 5

[[6]]
[1] 6

[[7]]
[1] 7

[[8]]
[1] 8

[[9]]
[1] 9

[[10]]
[1] 10

[[11]]
[1] 11

[[12]]
[1] 12

[[13]]
[1] 13

[[14]]
[1] 14

[[15]]
[1] 15

[[16]]
[1] 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]]
#> [1] 1 3
#> 
#> [[2]]
#> [1] 5 7
#> 
#> [[3]]
#> [1]  9 11
#> 
#> [[4]]
#> [1] 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.