如何挑出矩阵中的特定值 [R]

How to single out specific values in a matrix [R]

嗨,我有一个难题。我这里有一个矩阵:

         [,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

我的问题是如何在上面的矩阵中挑出最小的非零值。显然,如果我使用 min(A) 我会得到 0 作为我的答案,但我想要的是值 1.414214.

a 的最小值,其中 a 不等于 0

min(a[a!=0])

具有打印索引的功能:

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))
}

我们可以将 tail()which 一起使用:这里 mat 是您的矩阵

  1. 从第一个非零值
  2. 获取索引yourIndex
  3. 然后调用矩阵中的值
yourIndex <- tail(which(mat!=0),1)
mat[yourIndex]

OR shorter:

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

使用矩阵你可以做一个简单的 for 循环

min_numbers <- rep(NA,5)

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

min_numbers

但我更愿意在 tydiverse

上使用数据框