R:通过索引矩阵从矩阵中拾取值
我有一个包含n行和m列的数据矩阵(在本例中,n=192,m=1142)和一个nxp的索引矩阵(192x114)。Indie矩阵的每一行都显示了我想从datamatrix的匹配行中选择的元素的列号。因此,我有这样一种情况(带有示例值): 我尝试使用for循环:R:通过索引矩阵从矩阵中拾取值,r,matrix,subset,indices,picking,R,Matrix,Subset,Indices,Picking,我有一个包含n行和m列的数据矩阵(在本例中,n=192,m=1142)和一个nxp的索引矩阵(192x114)。Indie矩阵的每一行都显示了我想从datamatrix的匹配行中选择的元素的列号。因此,我有这样一种情况(带有示例值): 我尝试使用for循环: result<-0 for(i in 1:3) { result[i]<-data[i,][columnindices[,i]] print[i] } result您的循环只差一点点: result <- matri
result<-0
for(i in 1:3) {
result[i]<-data[i,][columnindices[,i]]
print[i]
}
result您的循环只差一点点:
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
result@LAP描述的for
循环方式更容易理解和实现
如果你想要一些通用的东西,也就是说,你不需要
每次调整行号时,您可以使用mapply
功能:
result <- mapply(
FUN = function(i, j) data[i,j],
row(columnindices),
columnindices)
dim(result) <- dim(columnindices)
结果您能解释列索引背后的合理性吗?您可以尝试ColumnIndicates这里形成的ColumnIndicates矩阵只是一个示例,实际上我有一个特定的列索引矩阵,显示特定元素的列。非常感谢!我很确定解决方案必须包含矩阵的某种子集,但现在我发现它没有。谢谢你的回答!对于将此函数用于大型数据集的人的提示(有些人可能很清楚,但我不这么认为):通过将数据和列索引转换为矩阵,似乎可以大大加快计算速度。使用xts对象尝试此操作,但计算从未结束。
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
result <- mapply(
FUN = function(i, j) data[i,j],
row(columnindices),
columnindices)
dim(result) <- dim(columnindices)