Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

which.max ties method in R

which.max and which.min will return the smallest index of the max or min value if there are ties.

Is there a way around this so that the largest index is returned without affecting the efficiency of the function?

max.col has this exact functionality, but I am dealing with a vector not a matrix.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do like this:

x<-c(1,2,1,4,3,4)
#identical to which.max, except returns all indices with max
which(x==max(x)) 
[1] 4 6
z<-which(x==max(x))
z[length(z)]
[1] 6
#or with tail
tail(which(x==max(x)),1)
[1] 6

edit:

Or, you could also use max.col function for vectors like this:

max.col(t(x),"last")
[1] 6
#or
max.col(matrix(x,nrow=1),"last")
[1] 6

edit: Some benchmarking:

x<-sample(1:1000,size=10000,replace=TRUE)
library(microbenchmark)
microbenchmark(which.max(x),{z<-which(x==max(x));z[length(z)]}, 
     tail(which(x==max(x)),1),max.col(matrix(x,nrow=1),"last"),
     max.col(t(x),"last"),which.max(rev(x)),times=1000)
Unit: microseconds
                                             expr     min      lq  median      uq       max neval
                                     which.max(x)  29.390  30.323  30.323  31.256 17550.276  1000
 {     z <- which(x == max(x))     z[length(z)] }  40.586  42.452  42.919  44.318   631.178  1000
                      tail(which(x == max(x)), 1)  57.380  60.646  61.579  64.844   596.657  1000
             max.col(matrix(x, nrow = 1), "last") 134.353 138.085 139.485 144.383   710.949  1000
                            max.col(t(x), "last") 116.159 119.425 121.291 125.956   729.610  1000
                                which.max(rev(x))  89.569  91.435  92.368  96.566   746.404  1000

So all methods seem to be slower than the original (which gives wrong result), but z <- which(x == max(x));z[length(z)] seems to be fastest option of these.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...