【问题标题】:How to Manipulate Array Indexed Values from Matrix in R [duplicate]如何从 R 中的矩阵操作数组索引值 [重复]
【发布时间】:2017-01-11 00:54:25
【问题描述】:

给定一个矩阵

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

假设你想要 1 的所有值 使用数组索引

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

如何在矩阵中操作这些索引值?

以下内容并没有完成我所追求的:

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

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

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

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

【问题讨论】:

    标签: r matrix indexing


    【解决方案1】:

    您在询问矩阵索引。 which返回的indx.1是一个2列的矩阵;您可以直接使用它来处理矩阵元素。这称为矩阵索引。所以试试mat[index.1]

    还请考虑这个玩具示例:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-22
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      相关资源
      最近更新 更多