如何在矩阵的行中找到第二高值。我的矩阵具有Na值。寻找最高值并没有带来任何问题,但寻找第二高的返回错误。
new_class <- max.col(memb)### for first highest value
n<- length(memb[i,k])
sort(memb,partial=n-1)[n-1]
Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) :
index 27334 outside bounds
以及如何找到具有第二高值的列
尝试以下:
# create amatrix with NA values
a <- runif(n=30)
a[sample(30,10)] <- NA
memb <- matrix(a, ncol=3)
memb
[,1] [,2] [,3]
[1,] 0.8534791 0.4881141 0.99065285
[2,] 0.7340371 0.7439187 0.13665397
[3,] 0.3355996 NA 0.24051520
[4,] NA 0.6561470 0.15877743
[5,] NA 0.3649768 0.84415732
[6,] NA NA NA
[7,] NA 0.1018859 0.75347257
[8,] 0.3918607 NA 0.04462168
[9,] 0.4653950 0.4043837 0.75119324
[10,] NA NA 0.54516193
# find second highest value (while omitting NA values)
apply(memb, 1, function(x){sort(na.omit(x), decreasing=F)[2]})
[1] 0.85347909 0.73403712 0.24051520 0.15877743 0.36497678 NA 0.10188592
[8] 0.04462168 0.46539497 NA
要找到第二高值的位置(列),请使用order
(如Brodieg所建议)
apply(memb, 1, function(x){order(na.omit(x), decreasing=T)[2]})
[1] 1 1 2 2 1 NA 1 2 1 NA
请注意,如果该行中只有一个非NA值,则返回NA