How to find the absolute maximum of each group in R data frame?

R ProgrammingServer Side ProgrammingProgramming

To find the absolute maximum of each group in R data frame, we can follow the below steps −

  • First of all, create a data frame.

  • Then, use summarise_each function of dplyr package along with which.max and abs function to find the absolute maximum of each group after grouping with group_by.

Example 1

Create the data frame

Let’s create a data frame as shown below −

x<-rnorm(25)
Grp<-sample(LETTERS[1:10],25,replace=TRUE)
df<-data.frame(x,Grp)
df

Output

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

      x       Grp
1   0.44813793 I
2  -0.42762853 F
3   1.84217825 D
4  -1.12661531 H
5   0.16377743 E
6  -0.30519746 F
7   1.68274689 D
8   0.20418659 C
9  -0.45494028 J
10 -0.80892645 G
11 -1.79420007 I
12  0.50946053 F
13  0.01846558 J
14  0.94334983 B
15 -0.41051915 A
16  0.85902521 I
17 -0.07774155 I
18 -0.14128810 C
19 -0.20461102 G
20  0.11894428 F
21  0.71705698 C
22  0.71409822 D
23  0.62682371 A
24 -0.03779485 F
25  0.34670072 A

Find the absolute maximum of each group

Using summarise_each function of dplyr package along with which.max and abs function to find the absolute maximum of each group for column x after grouping with group_by as shown below −

x<-rnorm(25)
Grp<-sample(LETTERS[1:10],25,replace=TRUE)
df<-data.frame(x,Grp)
library(dplyr)
df %>% group_by(Grp) %>% summarise_each(funs(.[which.max(abs(.))]))

Output

# A tibble: 10 x 2
   Grp  x
 <chr> <dbl>
1  A   0.627
2  B   0.943
3  C   0.717
4  D   1.84
5  E   0.164
6  F   0.509
7  G  -0.809
8  H  -1.13
9  I  -1.79
10 J  -0.455

Example 2

Create the data frame

Let’s create a data frame as shown below −

DV<-sample(-20:20,25)
Gender<-sample(c("Male","Female"),25,replace=TRUE)
dat<-data.frame(DV,Gender)
dat

Output

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

    DV Gender
1  -16 Male
2  -18 Female
3   20 Male
4   10 Female
5   1  Female
6  -1  Male
7   11 Male
8  -14 Female
9   4  Male
10 -17 Female
11 -9  Female
12   9 Female
13  12 Male
14   5 Male
15  -7 Male
16  14 Female
17   8 Female
18  19 Female
19 -8  Male
20 -19 Male
21  6  Male
22 18  Male
23 -3  Male
24 -5  Female
25 13  Female

Find the absolute maximum of each group

Using summarise_each function of dplyr package along with which.max and abs function to find the absolute maximum of each group for column DV after grouping with group_by as shown below −

DV<-sample(-20:20,25)
Gender<-sample(c("Male","Female"),25,replace=TRUE)
dat<-data.frame(DV,Gender)
library(dplyr)
dat %>% group_by(Gender) %>% summarise_each(funs(.[which.max(abs(.))]))

Output

# A tibble: 2 x 2
Gender    DV
 <chr>   <int>
1 Female -20
2 Male    17
raja
Published on 12-Nov-2021 06:30:07
Advertisements