如何在R中将值排名朝向0作为最低值?

huangapple go评论87阅读模式
英文:

How to rank values towards 0 as the lowest in R?

问题

我有一个包含负值和正值的向量。我想以这样的方式对它们进行排名,使接近0的值排名第一,而与0最远的值,无论符号如何,都应排名最高。以下是一个具有排名的示例数据:

  1. 数值 排名
  2. 0.817305499 8
  3. 0.22799983 5
  4. -0.015915982 1
  5. 0.271941164 6
  6. 0.851973536 9
  7. -0.679487051 7
  8. 0.09247952 2
  9. -1.047086596 10
  10. -0.174033279 3
  11. 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

  1. Value Rank
  2. 0.817305499 8
  3. 0.22799983 5
  4. -0.015915982 1
  5. 0.271941164 6
  6. 0.851973536 9
  7. -0.679487051 7
  8. 0.09247952 2
  9. -1.047086596 10
  10. -0.174033279 3
  11. 0.189823311 4

How can I achieve this in R?

答案1

得分: 2

你可以使用 order 按照 abs 进行排序:

  1. > with(df, df[order(abs(Value)), ])
  2. Value Rank
  3. 3 -0.01591598 1
  4. 7 0.09247952 2
  5. 9 -0.17403328 3
  6. 10 0.18982331 4
  7. 2 0.22799983 5
  8. 4 0.27194116 6
  9. 6 -0.67948705 7
  10. 1 0.81730550 8
  11. 5 0.85197354 9
  12. 8 -1.04708660 10

或者如果你只想创建一个新列,可以使用 rank

  1. > transform(df, Rank2 = rank(abs(Value)))
  2. Value Rank Rank2
  3. 1 0.81730550 8 8
  4. 2 0.22799983 5 5
  5. 3 -0.01591598 1 1
  6. 4 0.27194116 6 6
  7. 5 0.85197354 9 9
  8. 6 -0.67948705 7 7
  9. 7 0.09247952 2 2
  10. 8 -1.04708660 10 10
  11. 9 -0.17403328 3 3
  12. 10 0.18982331 4 4
英文:

You can use order by abs

  1. > with(df,df[order(abs(Value)), ])
  2. Value Rank
  3. 3 -0.01591598 1
  4. 7 0.09247952 2
  5. 9 -0.17403328 3
  6. 10 0.18982331 4
  7. 2 0.22799983 5
  8. 4 0.27194116 6
  9. 6 -0.67948705 7
  10. 1 0.81730550 8
  11. 5 0.85197354 9
  12. 8 -1.04708660 10

or rank if you just want to create a new column

  1. > transform(df, Rank2 = rank(abs(Value)))
  2. Value Rank Rank2
  3. 1 0.81730550 8 8
  4. 2 0.22799983 5 5
  5. 3 -0.01591598 1 1
  6. 4 0.27194116 6 6
  7. 5 0.85197354 9 9
  8. 6 -0.67948705 7 7
  9. 7 0.09247952 2 2
  10. 8 -1.04708660 10 10
  11. 9 -0.17403328 3 3
  12. 10 0.18982331 4 4

huangapple
  • 本文由 发表于 2023年6月12日 02:10:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76451875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定