Hi, I use the max function often to find the top value from a matrix or column of a data.frame. Now I'm looking to find the top 2 (or three) values from my data. I know that I could sort the list and then access the first two items, but that seems like the "long way". Is there some way to access "max_2" or similar? Thanks! -- Noah
Hi Noah, Next time try, please, send a short reproducible code/example. May be this can be (not so elegant but) helpfull myDF<-data.frame(cbind(a=runif(5),b=runif(5))) myDF N=2 a.order<-rev(order(myDF$a))[1:N] b.order<-rev(order(myDF$b))[1:N] myDF.max2a<-myDF[a.order,] myDF.max2a myDF.max2b<-myDF[b.order,] myDF.max2b milton On Thu, Sep 3, 2009 at 7:17 PM, Noah Silverman <noah@smartmediacorp.com>wrote:> Hi, > > I use the max function often to find the top value from a matrix or column > of a data.frame. > > Now I'm looking to find the top 2 (or three) values from my data. > > I know that I could sort the list and then access the first two items, but > that seems like the "long way". Is there some way to access "max_2" or > similar? > > > Thanks! > > -- > Noah > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html<http://www.r-project.org/posting-guide.html> > and provide commented, minimal, self-contained, reproducible code. >[[alternative HTML version deleted]]
Phil, That's perfect. (For my application, I've never seen a tie. While possible, the likelihood is almost none.) Thanks! -- Noah On 9/3/09 4:29 PM, Phil Spector wrote:> Noah - > max(x[-which.max(x)] will give you the second largest value, > but it doesn't handle ties. > x[order(x,decreasing=TRUE)[n]] will give you the nth largest > value, with the same caveat regarding ties. For example, > x[order(x,decreasing=TRUE)[1:3]] will give you the three largest > values. > > - Phil Spector > Statistical Computing Facility > Department of Statistics > UC Berkeley > spector@stat.berkeley.edu > > > On Thu, 3 Sep 2009, Noah Silverman wrote: > >> Hi, >> >> I use the max function often to find the top value from a matrix or >> column of a data.frame. >> >> Now I'm looking to find the top 2 (or three) values from my data. >> >> I know that I could sort the list and then access the first two >> items, but that seems like the "long way". Is there some way to >> access "max_2" or similar? >> >> >> Thanks! >> >> -- >> Noah >> >> ______________________________________________ >> R-help@r-project.org mailing list >> https://stat.ethz.ch/mailman/listinfo/r-help >> PLEASE do read the posting guide >> http://www.R-project.org/posting-guide.html >> and provide commented, minimal, self-contained, reproducible code. >>[[alternative HTML version deleted]]