topn: Highest elements in a vector.

Description Usage Arguments Value See Also Examples

View source: R/my_functions.r

Description

Finds the top elements in a vector very quickly. Equivalent ot -sort(-x, partial=1:n)

Usage

1
topn(x, n = 100, value = F, lowest = F)

Arguments

x

A numeric vector.

n

The number of top elements to return.

value

If TRUE, returns the values of the top elements. If FALSE, returns the indices.

lowest

If TRUE, returns the lowest elements instead of the highest.

Value

A vector containing the indices or the values of the top elements.

See Also

http://stackoverflow.com/questions/18450778/

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
naive_top <- function(x, n) {
   -sort(-x, partial=1:n)
}
x <- runif(1e7)
microbenchmark(naive_top(x,100), topn(x,100,value=T), times=10)

Unit: milliseconds
                   expr       min        lq     mean    median        uq
      naive_top(x, 100) 1070.0180 1071.5951 1075.964 1072.3520 1073.9989
topn(x, 100, value = T)  433.6682  433.8882  434.771  434.4986  435.6029

traversc/trqwe documentation built on Dec. 4, 2020, 4:21 a.m.