R:从索引矩阵中选取矩阵中的值

时间:2018-07-02 09:31:13

标签: r matrix subset indices picking

我有一个具有n行和m列的数据矩阵(在这种情况下,n = 192,m = 1142),索引矩阵为nxp(192x114)。索引矩阵的每一行都显示了我想从数据矩阵的匹配行中选取的元素的列号。因此,我遇到这样的情况(带有示例值):

data<-matrix(1:30, nrow=3)
data
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    4    7   10   13   16   19   22   25    28
[2,]    2    5    8   11   14   17   20   23   26    29
[3,]    3    6    9   12   15   18   21   24   27    30


columnindices<-matrix(sample(1:10,size=9, replace=TRUE),nrow=3)
columnindices
      [,1] [,2] [,3]
[1,]    8    7    4
[2,]   10    8   10
[3,]    8   10    2

我想使用in columnindices矩阵从datamatrix行中选择值,以便生成的矩阵看起来像这样

      [,1] [,2] [,3]
[1,]   22   19   10
[2,]   29   23   29
[3,]   24   30   6

我尝试使用for循环:

result<-0
for(i in 1:3) {
 result[i]<-data[i,][columnindices[,i]]
 print[i]
}

但是这并没有显示期望的结果。我想我的问题应该很简单地解决,但是不幸的是,无论工作了很多小时,还是进行了多次搜索,我仍然无法解决(我是菜鸟)。我真的很感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

您的循环仅需一点时间:

if game[i].lower() == 'x':

请注意,矩阵与您发布的预期结果不完全相同,因为示例result <- matrix(rep(NA, 9), nrow = 3) for(i in 1:3){ result[i,] <- data[i, columnindices[i,]] } > result [,1] [,2] [,3] [1,] 25 13 7 [2,] 29 29 23 [3,] 15 15 18 的代码与您在下面发布的矩阵不匹配。代码应该可以按需要工作。

答案 1 :(得分:0)

@LAP描述的for循环方式更易于理解和实现。

如果您想拥有通用的东西,即您不需要 每次都要调整行号,您可以使用mapply函数:

result <- mapply(
  FUN = function(i, j) data[i,j],
  row(columnindices),
  columnindices)
dim(result) <- dim(columnindices)

mapply遍历两个矩阵的每个元素,

  • row(columnindices)用于i行索引
  • columnindices用于j列索引。

它返回一个向量,您必须将其强制转换为初始columnindices维度。