How to use top_n function from dplyr to extract rows based on one column ordered in descending order in R?


To use top_n function from dplyr to extract rows based on one column ordered indescending order in R, we can follow the below steps −

  • First of all, create a data frame.

  • Then, use top_n function dplyr package along with arrange and desc function to extract rows based on one column ordered in descending order.

Example

Create the data frame

Let’s create a data frame as shown below −

x<-rnorm(25)
y<-rnorm(25)
z<-rnorm(25)
df<-data.frame(x,y,z)
df

Output

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

         x           y          z
1   1.08454409 -0.592046057  0.6585417
2   1.65592292 -0.265941582  1.2114817
3   0.95440090  1.470083462  0.6739091
4   0.06280736  1.084730080 -0.8584295
5  -0.04918568 -0.001605027  1.7565422
6   0.35331320  2.053520032  0.5908641
7   0.21018034  0.895508750 -1.9313533
8   0.78907443 -0.424032581  0.2284949
9   0.98025083  0.073661099  0.2703707
10  0.01489154 -1.141132107 -1.7172786
11  0.51234250 -0.639931256 -0.5090562
12  0.09545684  0.428505867 -0.9865289
13  0.50701056  0.235247092  0.3148251
14  1.13687902  0.293837030 -0.4454266
15  1.16216903  2.231980020 -0.2709523
16  0.13175251  0.580977886  2.1508614
17 -0.86654329  0.103780077 -0.2392656
18 -0.47974879 -0.885647792 -1.2632639
19 -0.22566103  1.324036551 -0.2278964
20 -0.90975779 -0.192113587  1.5349889
21 -0.70991831  1.788266163 -0.3879485
22 -0.04723729  0.105558093 -1.9307871
23  0.81483081  1.318454260 -1.1376648
24  0.02234493  0.915030839 -0.8694467
25 -1.04939721 -0.978056239 -1.3975816

Extract rows by ordering a column in descending order

Using top_n function dplyr package along with arrange and desc function to extract rows based on column x ordered in descending order as shown below −

x<-rnorm(25)
y<-rnorm(25)
z<-rnorm(25)
df<-data.frame(x,y,z)
library(dplyr)
top_n(df,10,x) %>% arrange(desc(x))

Output

        x          y         z
1  1.6559229 -0.2659416  1.2114817
2  1.1621690  2.2319800 -0.2709523
3  1.1368790  0.2938370 -0.4454266
4  1.0845441 -0.5920461  0.6585417
5  0.9802508  0.0736611  0.2703707
6  0.9544009  1.4700835  0.6739091
7  0.8148308  1.3184543 -1.1376648
8  0.7890744 -0.4240326  0.2284949
9  0.5123425 -0.6399313 -0.5090562
10 0.5070106  0.2352471  0.3148251

Updated on: 16-Nov-2021

635 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements