问题
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)
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]
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.
EDIT: I tried using mat2[rowInd,colInd]
, but this did not work.
Best,
Paul
回答1:
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
If you have another matrix B
which you want to update values according to iv
, just do
B[iv] <- replacement
Maybe for some reason you've separated row index and column index into rowInd
and colInd
. In that case, just use
cbind(rowInd, colInd)
as indexing matrix.
来源:https://stackoverflow.com/questions/40227994/best-way-to-feed-which-arr-ind-t-back-into-matrix-in-r