将哪个(,arr.ind = T)反馈回R中的矩阵的最佳方法? [英] Best way to feed which(,arr.ind=T) back into matrix in R?

查看:555
本文介绍了将哪个(,arr.ind = T)反馈回R中的矩阵的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经提取了一些我想看的元素的数组索引:

I have extracted the array indeces of some elements I want to look at as follows:

mat = matrix(0,10,10)

arrInd = which(mat ==0,arr.ind = T)

然后,我对该矩阵进行更多操作,最终得到一个向量或行rowInd和列colInd的向量.我希望这些索引将值插入另一个矩阵,例如mat2.但是我似乎无法找到一种方法,而无需自己循环或进行模块化算术计算.我意识到我可以采取类似

Then I do some more operations on this matrix and eventually end up with a vector or rows rowInd and a vector of columns colInd. I want us these indeces to insert values into another matrix, say mat2. But I can't seem to figure out a way to do this without looping or doing the modular arithmetic calculation myself. I realize I could take something like

mat2[rowInd*(colInd-1)+rowInd]

,以便转换回1-d索引.但是由于R通常具有内置函数来执行此类操作,所以我想知道是否还有其他更简洁的方法可以执行此操作?像which(,arr.ind=T)这样方便的数据操作函数看起来很方便,反之亦然.

in order to transform back to the 1-d indexing. But since R usually has built in functions to do this sort of thing, I was wondering if there is any more concise way to do this? It would just seem natural that such a handy data-manipulation function like which(,arr.ind=T) would have a handy inverse.

我尝试使用mat2[rowInd,colInd],但这不起作用.

I tried using mat2[rowInd,colInd], but this did not work.

最好

保罗

推荐答案

请阅读

Have a read on R intro: indexing a matrix on the use of matrix indexing. which(, arr.ind = TRUE) returns a two column matrix suitable for direct use of matrix indexing. For example:

A <- matrix(c(1L,2L,2L,1L), 2)
iv <- which(A == 1L, arr.ind = TRUE)

#     row col
#[1,]   1   1
#[2,]   2   2

A[iv]
# [1] 1 1

如果您要根据iv更新值的另一个矩阵B,只需执行

If you have another matrix B which you want to update values according to iv, just do

B[iv] <- replacement

也许出于某种原因,您已将行索引和列索引分为rowIndcolInd.在这种情况下,只需使用

Maybe for some reason you've separated row index and column index into rowInd and colInd. In that case, just use

cbind(rowInd, colInd)

作为索引矩阵.

这篇关于将哪个(,arr.ind = T)反馈回R中的矩阵的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆