R中的哪个最大联系方法 [英] which.max ties method in R

查看:77
本文介绍了R中的哪个最大联系方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

which.maxwhich.min将返回最大值或最小值的最小索引.

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具有此确切功能,但我要处理的是向量而不是矩阵.

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

推荐答案

您可以这样做:

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

或者,您也可以对以下矢量使用max.col函数:

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

一些基准测试:

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

因此所有方法似乎都比原始方法慢(这会导致错误的结果),但是z <- which(x == max(x));z[length(z)]似乎是这些方法中最快的选择.

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.

这篇关于R中的哪个最大联系方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆