【问题标题】:R: Picking values from matrix by indice matrixR:按索引矩阵从矩阵中选取值
【发布时间】:2018-07-02 09:31:12
【问题描述】:

我有一个 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 矩阵从数据矩阵行中选取值,以便生成的矩阵如下所示

      [,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]
}

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

【问题讨论】:

  • 你能解释一下columnindices背后的原因吗?你可以试试columnindices&lt;-matrix(sample(6:30,size=9, replace=TRUE),nrow=3)
  • 这里形成的 columnindices 矩阵只是一个例子,实际上我有一个特定的列索引矩阵来显示特定元素的列。

标签: r matrix subset indices picking


【解决方案1】:

你的循环有点偏离:

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

请注意,该矩阵与您发布的预期结果并不完全相同,因为您的示例代码 columnindices 与您在下面发布的矩阵不匹配。代码应该按照你的意愿工作。

【讨论】:

  • 非常感谢 LAP!我很确定解决方案必须包含矩阵的某种子集,但现在我发现它没有。
【解决方案2】:

@LAP 描述的for-loop 方式更容易理解和实现。

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

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

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

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

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

【讨论】:

  • 对使用此函数处理大型数据集的人的提示(这对某些人来说可能很明显,但对我来说不是):似乎可以通过将数据和列索引转换为矩阵。用 xts-object 试过这个,计算永远不会结束。
猜你喜欢
  • 1970-01-01
  • 2013-11-18
  • 2010-12-22
  • 1970-01-01
  • 2018-05-12
  • 2019-05-05
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多