如何从R中的矩阵操作数组索引值 [英] How to Manipulate Array Indexed Values from Matrix in R

查看:147
本文介绍了如何从R中的矩阵操作数组索引值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出矩阵

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

假设您要使用数组索引来使用1的所有值

say you want all the values of 1 using array indexing

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

因为据我所知,R索引了indx.1 [,1]和indx.1 [,2]的每个组合.

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

如果您使用arr.ind = FALSE,我知道这很容易,但是,我对arr.ind = TRUE感到好奇.例如:

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

感谢您的帮助!

推荐答案

您正在询问矩阵索引. which返回的indx.1是2列的矩阵;您可以直接使用它来处理矩阵元素.这称为矩阵索引.因此,尝试mat[index.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

这篇关于如何从R中的矩阵操作数组索引值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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