r - in matrices with NAs, finding second highest value in a row -


how find second highest value in rows of matrix. matrix has na values. looking highest values poses no problems looking second highest returns error.

new_class <- max.col(memb)### 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 how find column second highest value

try this:

# create amatrix na values <- 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 position (column) of second highest value, use order (as suggested 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 if there 1 non-na value in row, returns na


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -