Syntax error How to convert data frame values to their rank in R?

How to convert data frame values to their rank in R?



To convert data frame values to their rank in R, we can follow the below steps −

  • First of all, create a data frame.
  • Then, find the rank of each value using rank function with lapply.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

> x1<-rnorm(20)
> y1<-rnorm(20)
> df<-data.frame(x1,y1)
> df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

           x1          y1
1  -0.9045608  1.95315551
2  -1.6222122 -1.19880638
3   0.8618855 -0.33643175
4  -0.3547085 -0.18097356
5  -0.3043621 -0.60342210
6   0.5606001 -0.83618995
7  -1.1752752 -0.46651702
8   0.2009474 -0.39482238
9   0.3595199 -0.59964119
10 -0.6007706 -0.01499288
11  0.1972236  1.44063062
12  1.0988526  0.17336280
13  1.0016738  2.27343055
14  2.6411272 -0.21273651
15 -1.1907730  0.88769339
16  1.0993620  1.57416767
17 -0.6732082  2.44837538
18  2.7868490 -0.46566411
19  0.9185654 -1.51994397
20 -1.2386102  1.34563437

Convert data frame values into their ranks

Using rank function with lapply function to find the rank of each value in the data frame df −

> df[]<-lapply(-df,rank,ties.method="min")
> df

Output

   x1 y1
1  16  3
2  20 19
3  7  12
4  13 10
5  12 17
6  8  18
7  17 15
8  10 13
9  9  16
10 14  9
11 11  5
12 4   8
13 5   2
14 2  11
15 18  7
16 3   4
17 15  1
18 1  14
19 6  20
20 19  6
Updated on: 2021-08-13T09:17:48+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements