Home > Back-end >  How to single out specific values in a matrix [R]
How to single out specific values in a matrix [R]

Time:11-28

Hi i have a dilemma here. I have here with me a following matrix:

         [,1]     [,2]     [,3]     [,4]     [,5]
  [1,] 0.000000 1.414214 2.828427 4.242641 5.656854
  [2,] 1.414214 0.000000 1.414214 2.828427 4.242641
  [3,] 2.828427 1.414214 0.000000 1.414214 2.828427
  [4,] 4.242641 2.828427 1.414214 0.000000 1.414214
  [5,] 5.656854 4.242641 2.828427 1.414214 0.000000

My question here is how do I single out the least non-zero value in the matrix above. Clearly, if I used min(A) I would get 0 as my answer but what I want is the value 1.414214.

CodePudding user response:

min of a where a is not equal to 0

min(a[a!=0])

With a function to print index:

min_value <- function(M){
  
  minval <- min(M[M!=0])
  index <- which(M==minval, arr.ind=TRUE)
  
  print(paste("The smallest non-zero value (", minval, ") is located in:", sep=""))
  
  for(i in 1:nrow(index)){
    print(paste("row[", index[i, 1] ,"] and column[", index[i, 2], "]", sep="" ))
  }
  
  return(list(min_value=minval, index=index))
}

CodePudding user response:

We could use tail() together with which: here mat is your matrix

  1. get the index yourIndex from the first non-zero value
  2. then call the value in the matrix
yourIndex <- tail(which(mat!=0),1)
mat[yourIndex]

OR shorter:

mat[tail(which(mat!=0,1)
> mat[yourIndex]
[1] 1.414214

CodePudding user response:

Using a matrix you can do a simple for loop

min_numbers <- rep(NA,5)

for (i in 1:5){
  min_numbers[i] <- min(m[(m[,i] > 0),i])
}

min_numbers

But I would rather work with a data frame on tydiverse

  • Related