[R] Largest N Values Efficiently?

Gabor Grothendieck ggrothendieck at gmail.com
Mon Nov 12 00:53:52 CET 2007


You can apply 1:n to order(x) so you don't wind up
subscripting x by every element in order(x).

o <- head(order(x), n) # positions
x[o]

A completely different approach, if X is a data frame with d as a data
column is this where the row names give the positions (don't know
about speed):

> library(sqldf)
> n <- 3
> X <- data.frame(d = c(5, 4, 6, 3, 10, 1, 12, 2))
> sqldf(paste("select * from X order by d limit", n), row.names = TRUE)
  d
6 1
8 2
4 3

On Nov 11, 2007 6:43 PM, David Katz <david at davidkatzconsulting.com> wrote:
>
> What is the most efficient alternative to x[order(x)][1:n] where
> length(x)>>n?
> I also need the positions of the mins/maxs perhaps by preserving names.
>
>  Thanks for any suggestions.
> --
> View this message in context: http://www.nabble.com/Largest-N-Values-Efficiently--tf4788033.html#a13697535
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at 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.
>



More information about the R-help mailing list