How to Manipulate Array Indexed Values from Matrix in R [duplicate]

左心房为你撑大大i 提交于 2019-12-11 05:31:14

问题


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:

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

Thanks for the help!


回答1:


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


来源:https://stackoverflow.com/questions/39300325/how-to-manipulate-array-indexed-values-from-matrix-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!