R: Get the row and column name of the minimum element of a matrix but with minimum != 0

亡梦爱人 提交于 2019-12-23 06:27:19

问题


I've got a matrix with a lot of zeros and with positive numerical values. I want to get the row and column number for which the element is the minimal NONZERO value of the matrix.

I don't find that min() has extra options to exclude zero, so how can I handle this?


回答1:


Seems like there could be a shorter answer but u can replace the zeros with NA and use na.rm=T

test = matrix(c(0:9,0:9),nrow =4,ncol=5)
test[which(test==0)] = NA
minValue = min(test,na.rm=T) 
rows = which(apply(test,1,min,na.rm=T)==minValue)
cols = which(apply(test,2,min,na.rm=T)==minValue)

Allows for duplicates




回答2:


Using x[x>0] you can directly find your nonzero element, but as you want row number and column number you have to give extra effort. I have used apply method for the same, which will return you index for row number and column number...

set.seed(1234)

set.seed(1234)
myMat = matrix(sample(0:1,replace=T,25),nrow=5)
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    1    1    1    0
[2,]    1    0    1    0    0
[3,]    1    0    0    0    0
[4,]    1    1    1    0    0
[5,]    1    1    0    0    0

#Defining a function which will return zero valued member index
FindIndex = function(x){
  v=vector()
  j=1
  for(i in 1:length(x)){
    if(x[i]>0){
      v[j]=i
      j=j+1
    }
  }
  return = v
}

#Find column number row-wise
apply(myMat, 1, FUN=FindIndex)

[[1]]
[1] 2 3 4

[[2]]
[1] 1 3

[[3]]
[1] 1

[[4]]
[1] 1 2 3

[[5]]
[1] 1 2

#Find row number column-wise
apply(myMat, 2, FUN=FindIndex)

[[1]]
[1] 2 3 4 5

[[2]]
[1] 1 4 5

[[3]]
[1] 1 2 4

[[4]]
[1] 1

[[5]]
logical(0)

You can convert this return values to your required format..



来源:https://stackoverflow.com/questions/24007875/r-get-the-row-and-column-name-of-the-minimum-element-of-a-matrix-but-with-minim

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