Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rank per row over multiple columns in R

Tags:

r

rank

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
like image 457
teeglaze Avatar asked Mar 06 '14 14:03

teeglaze


1 Answers

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
like image 105
Matthew Plourde Avatar answered Nov 10 '22 00:11

Matthew Plourde