Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decreasing Partial Sorting

Tags:

sorting

r

As ?sort said, if the argument partial is not NULL, it is taken to contain indices of elements of the result which are to be placed in their correct positions in the sorted array by partial sorting. You can read Argument “partial” of the sort function in R for detail. So in the case that I need to find the smallest 5 numbers in x <- sample(1:100, 50), then

sort(x, partial = 1:5)[1:5]

will be faster than

sort(x)[1:5]

However, how could I find the largest 5 numbers with partial sorting? Intuitively, I try to use:

sort(x, partial = 1:5, decreasing = T)

but it gets

Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) : unsupported options for partial sorting

Therefore, my question is how to achieve the effect of efficiency in this case.

like image 304
Darren Tsai Avatar asked Dec 10 '22 04:12

Darren Tsai


1 Answers

You can take the tail from the sorted vector:

set.seed(42)
x <- sample(1:100, 50)
# sort(x, partial = 1:5)[1:5] ## head

p <- length(x)+1 - (1:5) ## tail
sort(x, partial = p)[p]

If you want you can reverse the result using rev()

like image 175
jogo Avatar answered Jan 08 '23 21:01

jogo