Alex Miller - 1 year ago 55

R Question

Given a matrix

`mat = matrix(round(runif(min=0,max=1,n=9*9)),ncol=9,nrow=9)`

say you want all the values of 1

`indx.1 = which(mat == 1, arr.ind=TRUE)`

The below doesn't accomplish what I am after:

`result.i.dont.want = mat`

result.i.dont.want[indx.1[,1],indx.1[,2]] = NA

because, as far as I can tell, R indexes over every combination of indx.1[,1], and indx.1[,2].

I know this is very easy if you use arr.ind=FALSE, however, I am curious for arr.ind=TRUE. For example:

`result.i.do.want = mat`

result.i.do.want[which(mat == 1)] = NA

Thanks for the help!

Answer Source

You are asking about matrix indexing. `indx.1`

returned by `which`

is a matrix of 2 columns; you can use it directly to address matrix elements. This is known as matrix indexing. So try `mat[index.1]`

.

Also consider this toy example:

```
A <- matrix(1:9, 3, 3)
A[1:2, 1:2]
# [,1] [,2]
#[1,] 1 4
#[2,] 2 5
A[cbind(1:2, 1:2)]
# [1] 1 5
```