# How to find the groupwise order of values in an R data frame?

To find the groupwise order of values in an R data frame, we can use mutate function of dplyr package along with rank function and grouping will be done with the help of group_by function.

For Example, if we have a data frame called df that contains two columns say Group and DV then we can find the groupwise order of DV values by using the command given below −

df%%group_by(Group)%%mutate(Order=rank(DV))

## Example 1

Following snippet creates a sample data frame −

Group<-rep(LETTERS[1:5],each=4)
Score<-sample(1:50,20)
df1<-data.frame(Group,Score)
df1

The following dataframe is created

  Group  Score
1     A     13
2     A     27
3     A     50
4     A     42
5     B     43
6     B     20
7     B     45
8     B     49
9     C     31
10    C     15
11    C     26
12    C     33
13    D     40
14    D     38
15    D     12
16    D     17
17    E     16
18    E     28
19    E      5
20    E      9

To load dplyr package and find groupwise order of Score in df1 on the above created data frame, add the following code to the above snippet −

Group<-rep(LETTERS[1:5],each=4)
Score<-sample(1:50,20)
df1<-data.frame(Group,Score)
library(dplyr)
df1%%group_by(Group)%%mutate(Order=rank(Score))
# A tibble: 20 x 3
# Groups: Group [5]

## Output

If you execute all the above given snippets as a single program, it generates the following Output −

Group Score Order
<chr  <int <dbl
1  A    13  1
2  A    27  2
3  A    50  4
4  A    42  3
5  B    43  2
6  B    20  1
7  B    45  3
8  B    49  4
9  C    31  3
10 C    15  1
11 C    26  2
12 C    33  4
13 D    40  4
14 D    38  3
15 D    12  1
16 D    17  2
17 E    16  3
18 E    28  4
19 E     5  1
20 E     9  2

## Example 2

Following snippet creates a sample data frame −

Category<-rep(c("I","II","III","IV"),each=5)
Sales<-sample(51:100,20)
df2<-data.frame(Category,Sales)
df2

The following dataframe is created

 Category Sales
1   I      97
2   I      66
3   I      75
4   I      80
5   I      63
6  II      69
7  II      84
8  II      72
9  II      59
10 II      65
11 III     68
12 III     73
13 III     88
14 III     93
15 III    100
16 IV      58
17 IV      83
18 IV      95
19 IV      61
20 IV      67

To find groupwise order of Sales in df2 on the above created data frame, add the following code to the above snippet −

Category<-rep(c("I","II","III","IV"),each=5)
Sales<-sample(51:100,20)
df2<-data.frame(Category,Sales)
df2%%group_by(Category)%%mutate(Order=rank(Sales))
# A tibble: 20 x 3
# Groups: Category [4]


## Output

If you execute all the above given snippets as a single program, it generates the following Output −

Category Sales Order
<chr <int <dbl
1   I   97  5
2   I   66  2
3   I   75  3
4   I   80  4
5   I   63  1
6  II   69  3
7  II   84  5
8  II   72  4
9  II   59  1
10 II   65  2
11 III  68  1
12 III  73  2
13 III  88  3
14 III  93  4
15 III 100  5
16 IV   58  1
17 IV   83  4
18 IV   95  5
19 IV   61  2
20 IV   67  3