# in matrices with NAs, finding second highest value in a row

how to find the second highest value in rows of a matrix. my matrix has NA values. looking for the highest values poses no problems but looking for the second highest returns an error.

```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
```

and also how to find the column with the second highest value

Try this:

```# 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
```

To find the position (column) of the second highest value, use order (as suggested by BrodieG)

```apply(memb, 1, function(x){order(na.omit(x), decreasing=T)[2]})
[1]  1  1  2  2  1 NA  1  2  1 NA
```

Note that if there is only one non-NA value in the row, this returns NA