Return the indices of the top or bottom abs(n) elements of a
vector, with several methods for resolving ties.
Usage
which_top_n(x, n, tied = c("given", "all", "none"))Arguments
- x
a vector on which
rank()can be evaluated.- n
the number of elements to attempt to select; if positive top
nare selected, and if negative bottom-n.- tied
a string to specify how to handle multiple elements tied for
n'th place:allornoneto include all or none of the tied elements, returning a longer or shorter vector thann, respectively;given(the default) to use the order in which the elements are found inx.
Value
An integer vector of indices on x, with an attribute
attr(, "tied") with the indicies of the tied elements (possibly
empty).
Examples
(x <- rep(1:4, 1:4))
#> [1] 1 2 2 3 3 3 4 4 4 4
stopifnot(identical(which_top_n(x, 5, "all"), structure(4:10, tied = 4:6)))
stopifnot(identical(which_top_n(x, 5, "none"), structure(7:10, tied = 4:6)))
stopifnot(identical(which_top_n(x, 5), structure(6:10, tied = 4:6)))
stopifnot(identical(which_top_n(x, -5, "all"), structure(1:6, tied = 4:6)))
stopifnot(identical(which_top_n(x, -5, "none"), structure(1:3, tied = 4:6)))
stopifnot(identical(which_top_n(x, -5), structure(1:5, tied = 4:6)))