Alex Miller Alex Miller - 8 months ago 34
R Question

How to Manipulate Array Indexed Values from Matrix in R

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 using array indexing

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

How do you manipulate those index values within your matrix?

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: = mat[which(mat == 1)] = NA

Thanks for the help!


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