Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between sort() and sort.list() in R?

Tags:

r

Well, having decided to get to know some of the basic functions in R I've stumbled upon the sort.list() function. I get the pretty straight forward sort() function, but don't get the idea of the sort.list(). I've read that it should be a permutation function rearranging the content of my vector (in some way).

Having the vector;

x <- c(5.0, 3.0, 2.0, 2.2, 0.0, 5.0, 3.0, 2.0, 2.2)

Running sort.list(x) outputs

[1] 5 3 8 4 9 2 7 1 6

Where did that come from? Can someone give me a hint please? And what's the use of this permutation anyway?

Thanks.

like image 313
Alex Avatar asked May 01 '12 15:05

Alex


1 Answers

sort.list, as it says at ?sort.list, is the same as order, only instead of accepting multiple arguments via ..., it accepts only one atomic vector as an argument.

Presumably, then, it could be intended as a "faster" or "simpler" version of order.

What good is it? Consider this:

x <- c(5.0, 3.0, 2.0, 2.2, 0.0, 5.0, 3.0, 2.0, 2.2)
> x[sort.list(x)]
[1] 0.0 2.0 2.0 2.2 2.2 3.0 3.0 5.0 5.0
> x[order(x)]
[1] 0.0 2.0 2.0 2.2 2.2 3.0 3.0 5.0 5.0

Just like order it returns a permutation that when used to index the original vector sorts it.

But I also think the name is confusing.

like image 186
joran Avatar answered Sep 26 '22 00:09

joran