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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With