-2

Suppose a list called list_x is made up of 10 different matrices, the dim of all these matrices is 5 * 3. Now, what I want to do is:

  • Extract the first column of each matrix and vertically merged into a new matrix A
  • Extract the second column of each matrix and vertically merged into a new matrix B
  • Extract the third column of each matrix and vertically merged into a new matrix C

I thought of it, but just can write here

sapply(list_X, function(x) x[,1])

Thank for any help.

MLavoie
  • 9,671
  • 41
  • 36
  • 56
Grace_G
  • 53
  • 1
  • 8
  • Hi Grace, can you please add a [Minimum Working Example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with data to your question. – David Sep 19 '17 at 08:08
  • list_X <- list(matirx1, matirx2, matirx3) # #actually, the number of matrix is 10 > list_X [[1]] [,1] [,2] [,3] [1,] 1 6 11 [2,] 2 7 12 [3,] 3 8 13 [4,] 4 9 14 [5,] 5 10 15 [[2]] [,1] [,2] [,3] [1,] 11 16 21 [2,] 12 17 22 [3,] 13 18 23 [4,] 14 19 24 [5,] 15 20 25 [[3]] [,1] [,2] [,3] [1,] 36 41 46 [2,] 37 42 47 [3,] 38 43 48 [4,] 39 44 49 [5,] 40 45 50 – Grace_G Sep 19 '17 at 08:28

1 Answers1

0
list_X <- replicate(10, matrix(1:15, 5, 3), simplify = F)

A little dirty but this will do the trick (not sure what exactly you mean by vertically merge).

lapply(1:3, function(y) sapply(1:10, function(x) list_X[[x]][,y]))
sedsiv
  • 531
  • 1
  • 3
  • 15
  • two amazing commond lines, sample but realize complex function. by the way, vertically merge, how to say, like cbind() function, not clear expression:PThank you! – Grace_G Sep 19 '17 at 08:46
  • Then put a transpose before the `sapply`, like `t(sapply(...))` – sedsiv Sep 19 '17 at 08:51
  • Got it, your code level is so good. However, until today I know lapply(1:3...) can accept vector... – Grace_G Sep 19 '17 at 09:16