Extracts the indecies of the \(n\) largest elements of the input.
This procedure is equivalent to order(x, decreasing = TRUE)[1:n_elements]
,
but is much faster and avoids the overhead of sorting discarded elements.
This function is useful for extracting the rows in a data frame having the
largest values in one of the columns.
partial_argsort(x, n_elements)
Numeric vector, the indecies of the largest elements (in sorted order) in
x
.
x <- c(10L,5L,-2L,12L,15L)
max_indecies <- partial_argsort(x,3L)
max_indecies
#> [1] 5 4 1
x[max_indecies]
#> [1] 15 12 10
order(x)[1:3]
#> [1] 3 2 1
mtcars[partial_argsort(mtcars$hp,5L),]
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Maserati Bora 15.0 8 301 335 3.54 3.570 14.60 0 1 5 8
#> Ford Pantera L 15.8 8 351 264 4.22 3.170 14.50 0 1 5 4
#> Duster 360 14.3 8 360 245 3.21 3.570 15.84 0 0 3 4
#> Camaro Z28 13.3 8 350 245 3.73 3.840 15.41 0 0 3 4
#> Chrysler Imperial 14.7 8 440 230 3.23 5.345 17.42 0 0 3 4