2

Suppose I have 2 matrices m and m.ind. The first one contains actual data while the smaller one contains row indices.

 m
            [,1]       [,2]       [,3]       [,4]
[1,]  0.23094453 -0.1379296  0.4173233 -1.7767756
[2,] -1.15772946 -0.1111935  1.0654023  0.6228674
[3,]  0.24707599 -0.6900143  0.9702020 -0.5222834
[4,] -0.09111356 -0.2217942 -0.1016292  1.3222310
[5,]  1.75737562  0.1829077  1.4032035 -0.3634403

 m.ind
     [,1] [,2] [,3] [,4]
[1,]    2    1    3    5
[2,]    2    2    4    4

I would like to create a subset of the matrix m whose row ids are the elements of the matrix m.ind.

 m.sub
          [,1]       [,2]       [,3]       [,4]
[1,] -1.157729 -0.1379296  0.9702020 -0.3634403
[2,] -1.157729 -0.1111935 -0.1016292  1.3222310

I tried the function below:

test=apply(m, 2, function(x) x[m.ind])

Your assistance is appreciated.

  • 1
    Please make your problem **[easily reproducible](http://stackoverflow.com/a/28481250/2725969)**; notice how Marat did this for you, try do so yourself next time. – BrodieG Feb 24 '15 at 22:01

1 Answers1

2

You could produce the indices for subsetting m by either

m.ind2 <- m.ind + nrow(m)*(col(m.ind)-1)

or

m.ind2 <- cbind(as.vector(m.ind),as.vector(col(m.ind)))

And then do:

matrix(m[m.ind2],nrow=nrow(m.ind))

This solution employs the fact that matrix in R is essentially a vector with dim attributes.

Here is a sample data set:

set.seed(1)
m <- matrix(runif(20),ncol=4)
m.ind <- matrix(c(2,2,1,2,3,4,5,4),nrow=2)

and output:

          [,1]      [,2]      [,3]      [,4]
[1,] 0.3721239 0.8983897 0.6870228 0.7774452
[2,] 0.3721239 0.9446753 0.3841037 0.3800352
Marat Talipov
  • 13,064
  • 5
  • 34
  • 53