Cairo
Cairo

Reputation: 21

order() function gives wrong order for characters in R

xx = c("calculated_p3", "calculated_c1" ,"calculated_p2" ,"calculated_c2", "calculated_d2",
"calculated_d3", "calculated_c3", "calculated_p1" ,"calculated_d1")

order(xx)

The output is: 2 4 7 9 5 6 8 3 1

Why is the "calculated_d1" ordered as the first element? And why is "calculated_c2" ordered as the 9th element? I don't understand here. Shouldn't "calculated_c1" be the first one?

Thank you for your help

Upvotes: 0

Views: 280

Answers (2)

Florian
Florian

Reputation: 1258

If you want to keep your order you can use factors:

factor(xx, xx)
[1] calculated_p3 calculated_c1 calculated_p2 calculated_c2 calculated_d2 calculated_d3 calculated_c3 calculated_p1
[9] calculated_d1
9 Levels: calculated_p3 calculated_c1 calculated_p2 calculated_c2 calculated_d2 calculated_d3 ... calculated_d1

Upvotes: 0

Daniel V
Daniel V

Reputation: 1386

order is written such that xx[order(xx)] is the same as sort(xx).

The numbers don't refer to the position that each entry should go to but rather the position the entries should come from if they were in order.

calculated_c1 should indeed be the first one. As it is in position 2, the first number is therefore a 2.

Upvotes: 2

Related Questions