Dario Federici Dario Federici - 1 month ago 6
R Question

R extract values from matrix given dataframe of x and y

How can I extract values from a matrix given a data frame containing the indexes of Rows and Columns?

So, I have a matrix and I have a data frame with two columns the first contains the indexes of the rows that I want to extract from the matrix and the second the indexes of the columns.

How can I get all the values from the matrix corresponding to the couples of indexes in the data frame?

Answer

Without having more detail, my guess is you have a data.frame like so:

index_df = data.frame(rows = c(1:5),
                      cols = c(6:10))
> index_df
  rows cols
1    1    6
2    2    7
3    3    8
4    4    9
5    5   10

I will use this matrix as an example:

dummy_matrix = matrix(1:100, ncol = 10, byrow = T)

> dummy_matrix
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1    2    3    4    5    6    7    8    9    10
 [2,]   11   12   13   14   15   16   17   18   19    20
 [3,]   21   22   23   24   25   26   27   28   29    30
 [4,]   31   32   33   34   35   36   37   38   39    40
 [5,]   41   42   43   44   45   46   47   48   49    50
 [6,]   51   52   53   54   55   56   57   58   59    60
 [7,]   61   62   63   64   65   66   67   68   69    70
 [8,]   71   72   73   74   75   76   77   78   79    80
 [9,]   81   82   83   84   85   86   87   88   89    90
[10,]   91   92   93   94   95   96   97   98   99   100

Extract required entries:

dummy_matrix[as.matrix(index_df)]
[1]  6 17 28 39 50

thanks to those who spotted my silly error

Comments