I have a vector that contains both negative and positive values. I want to rank them in such a way that values close to 0 gets 1st rank and the values farthest from 0 irrespective of sign should get the highest rank. Here is one example data with ranks
Value Rank
0.817305499 8
0.22799983 5
-0.015915982 1
0.271941164 6
0.851973536 9
-0.679487051 7
0.09247952 2
-1.047086596 10
-0.174033279 3
0.189823311 4
How can I achieve this in R?
>Solution :
You can use order by abs
> with(df,df[order(abs(Value)), ])
Value Rank
3 -0.01591598 1
7 0.09247952 2
9 -0.17403328 3
10 0.18982331 4
2 0.22799983 5
4 0.27194116 6
6 -0.67948705 7
1 0.81730550 8
5 0.85197354 9
8 -1.04708660 10
or rank if you just want to create a new column
> transform(df, Rank2 = rank(abs(Value)))
Value Rank Rank2
1 0.81730550 8 8
2 0.22799983 5 5
3 -0.01591598 1 1
4 0.27194116 6 6
5 0.85197354 9 9
6 -0.67948705 7 7
7 0.09247952 2 2
8 -1.04708660 10 10
9 -0.17403328 3 3
10 0.18982331 4 4