Rank per row over multiple columns in R

£可爱£侵袭症+ 提交于 2019-11-26 20:59:39

问题


I'm using R for the analysis of my masterthesis. Unfortunately, I got stuck with this problem:

I would like to compute a new variable which calculates the rank of one variable per row within many variables.

Example:

V1    V2    V3   NewVariable_V1 NewVariable_V2 NewVariable_V3
11    21    35   3              2               1
22    12    66   2              3               1
44    22    12   1              2               3

回答1:


You're looking for rank. To get decreasing order, first negate the data.frame.

data.frame(d, t(apply(-d, 1, rank, ties.method='min')))
#   V1 V2 V3 V1.1 V2.1 V3.1
# 1 11 21 35    3    2    1
# 2 22 12 66    2    3    1
# 3 44 22 12    1    2    3



回答2:


?rank and see how to handle ties.

x <- cbind(a=c(11,22,44),
       b=c(21,12,22),
       c=c(35,66,12))
> x
      a  b  c
[1,] 11 21 35
[2,] 22 12 66
[3,] 44 22 12

EDITED 2018-10-22

Now, rank on

rows

 t(apply(-x, 1, rank))
     a b c
[1,] 3 2 1
[2,] 2 3 1
[3,] 1 2 3

or columns

apply(x, 2, rank)
     a b c
[1,] 3 1 3
[2,] 2 2 1
[3,] 1 3 2


来源:https://stackoverflow.com/questions/22227828/rank-per-row-over-multiple-columns-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!