Home > Blockchain >  Order function not working as expected in R
Order function not working as expected in R

Time:10-17

I am using the built-in state.x77 dataset in R, loaded through: data(state).

The incomes per capita of the 50 states are extracted through unname(state.x77[,2]):

 [1] 3624 6315 4530 3378 5114 4884 5348 4809 4815 4091 4963 4119 5107 4458 4628 4669 3712 3545
[19] 3694 5299 4755 4751 4675 3098 4254 4347 4508 5149 4281 5237 3601 4903 3875 5087 4561 3983
[37] 4660 4449 4558 3635 4167 3821 4188 4022 3907 4701 4864 3617 4468 4566

The highest income per capita (6315) is the second state in the dataset. However, when I type order(state.x77[,2]), it tells me that the second state in the dataset has the 4th lowest income:

[1] 24  4 18 31 48  1 40 19 17 42 33 45 36 44 10 12 41 43 25 29 26 38 14
[24] 49 27  3 39 35 50 15 37 16 23 46 22 21  8  9 47  6 32 11 34 13  5 28
[47] 30 20  7  2

What am I doing wrong?

CodePudding user response:

To add more to what Dany provided in comments, the order function returns the index of the states ordered by income from lowes to highest. For instance in your output it means, State 24 has the lowest income, state 4 has the second lowest income.

If you want to see from highest income to lowest income you need to write order(state.x77[,2], decreasing = TRUE).

Even better you can sort the whole matrix so that you can have the state names.

state.x77[order(state.x77[,2], decreasing = TRUE),]
  •  Tags:  
  • r
  • Related