R从给定的x和y数据帧的矩阵中提取值

R从给定的x和y数据帧的矩阵中提取值

本文介绍了R从给定的x和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?

推荐答案

在没有更多细节的情况下,我的猜测是您具有这样的data.frame:

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

提取必填项:

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

感谢那些发现我愚蠢错误的人

thanks to those who spotted my silly error

这篇关于R从给定的x和y数据帧的矩阵中提取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 23:56