在R中通过矩阵的更快方法

在R中通过矩阵的更快方法,r,R,我有一个巨大的矩阵变量mat,有M行和N列。我需要找到所有非零的位置。目前我正在编写以下代码来实现这一点 Rowindex_set = c() #Generate the set of all row indexes of all non-zero entries Colindex_set = c() #Generate the set of all col indexes of all non-zero entries for(i in 1:M){ for(j in 1:N){ i

我有一个巨大的矩阵变量mat,有M行和N列。我需要找到所有非零的位置。目前我正在编写以下代码来实现这一点

Rowindex_set = c() #Generate the set of all row indexes of all non-zero entries
Colindex_set = c() #Generate the set of all col indexes of all non-zero entries
for(i in 1:M){
  for(j in 1:N){
    if (mat[i,j] != 0){
      Rowindex_set = c(Rowindex_set,i)
      Colindex_set = c(Colindex_set,j)  
    }
  }
}
M和N通常在一万范围内。因此,这段代码需要很多时间。有没有更快的方法

编辑: 我做了一些修改,提出了一个更快的实现

Rowindex_set = rep.int(0,M*N) #Large vector of zeros
Colindex_set = rep.int(0,M*N) #Large vector of zeros
IndexCounter = 1
for(i in 1:M){
  for(j in 1:N){
    if (incomp_mat[i,j] != marker){
      Rowindex_set[IndexCounter] = i #Update each entry, rather than appending as earlier
      Colindex_set[IndexCounter] = j #Similar as above comment
      IndexCounter = IndexCounter + 1
    }
  }
}
Rowindex_set = Rowindex_set[-IndexCounter:-(M*N)] # Remove trailing zeros
Colindex_set = Colindex_set[-IndexCounter:-(M*N)] # Remove trailing zeros

因此,我没有在每次迭代中将新条目添加到Rowindex_集和Colindex_集,而是将它们初始化为一个较大的零向量,然后更新每个条目。最后,我删除了剩余的条目

,然后您要做什么?基于此,你可以使它非常快。根本不需要写循环。例如,如果必须用NA替换0,则可以这样做

M <- matrix(c(1,2,3,0,0,2),nrow=2)
M[M==0] <- NA

## OR change all nonzero elements

M[M!=0] <- NA 

这是一个列式非零索引列表

检查哪个函数的参数arr.ind。@Pascal请将此作为答案添加。@dineshdileep-完全可以/建议在这种情况下,您自己发布答案,然后在强制等待2天后接受它。干杯。正如帕斯卡在上面提到的,试试看=0,arr.ind=true之后我做的是一个非常复杂的算法。到目前为止,这段代码的运行速度比这快得多,我对它的执行速度很满意。@JoshO'Brien如果我使用它,我会得到行索引和列索引吗?@dineshdileep-R的优点在于它是交互式的。试试看!扰流板-是的,是的!!你是对的。我为这件小事道歉:
apply(M,2,function(x) which(x!=0))