英文:
How to rank values towards 0 as the lowest in R?
问题
我有一个包含负值和正值的向量。我想以这样的方式对它们进行排名,使接近0的值排名第一,而与0最远的值,无论符号如何,都应排名最高。以下是一个具有排名的示例数据:
数值 排名
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
我该如何在R中实现这个目标?
英文:
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?
答案1
得分: 2
你可以使用 order
按照 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
或者如果你只想创建一个新列,可以使用 rank
:
> 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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论