Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The output of 'order' not making sense to me [duplicate]

Tags:

r

For whatever reason I cannot get my head around what the function 'order' is actually doing. In the following code I show some data, what order returns, and then what I had naively thought order should return but doesn't. To me it seems like columns 3,4,5,6 & 7 are incorrect but I suspect it's just that order's documentation isn't getting through my dumb head.

x1 = c(1,1,3:1,1:4,3)
Ordered = order(x1)
MarkThinks = c(1,2,7,5,3,4,6,8,10,9)
Res1 = rbind(x1, Ordered, MarkThinks)

Res1

When run here I get:

> Res1
           [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
x1            1    1    3    2    1    1    2    3    4     3
Ordered       1    2    5    6    4    7    3    8   10     9
MarkThinks    1    2    7    5    3    4    6    8   10     9

In my mind ordering would mean that the four 1's in row 1 would generate 1,2,3,4 in their positions, followed by the two 2's generating 5,6, the three 3's 7, 8, 9 and the one 4 generating 10. In my application it's not important how ties are broken so I've just gone left to right but any order for ties is acceptable.

Assuming order is working correctly and not what I need here (i.e. - some option I haven't figured out yet) how would I get what I'm looking for in line 3?

like image 732
LGTrader Avatar asked Nov 28 '25 10:11

LGTrader


1 Answers

Your Ordered variable is misnamed. What order returns are the indices of the ordered vector – i.e. the subsetting indices necessary to get the elements in sorted order. So the following returns the ordered elements:

> ordered_indices = order(x1)
> ordered = x1[ordered_indices]

The MarkThinks output can be achieved using rank which, as the name indicates, literally returns the rank for each element (but does several different things when elements tie):

> ranked = rank(x1, ties.method = 'first')
> rbind(x1, ordered_indices, ordered, ranked)
                [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
x1                 1    1    3    2    1    1    2    3    4     3
ordered_indices    1    2    5    6    4    7    3    8   10     9
ordered            1    1    1    1    2    2    3    3    3     4
ranked             1    2    7    5    3    4    6    8   10     9
like image 71
Konrad Rudolph Avatar answered Nov 30 '25 23:11

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!