How to find the maximum of each row in an R data frame?


Sometimes we need maximum values, it helps us to identify which case or subject occurs at the greatest point hence we can understand the limit for the sample or population under study. If we want to find the maximum of values two or more columns for each row in an R data frame then pmax function can be used.

Example

Consider the below data frame −

 Live Demo

set.seed(1997)
x1<-rpois(20,5)
x2<-rpois(20,5)
df1<-data.frame(x1,x2)
df1

Output

  x1 x2
1  3 4
2  6 3
3  7 3
4  6 2
5  3 0
6  6 5
7  5 6
8  8 4
9  2 5
10 4 3
11 5 2
12 4 9
13 8 5
14 1 3
15 6 4
16 4 9
17 2 8
18 5 4
19 2 4
20 4 3

Finding maximum value in each row −

Example

df1$Max<-pmax(df1$x1,df1$x2)
df1

Output

  x1 x2 Max
1  3 4    4
2  6 3    6
3  7 3    7
4  6 2    6
5  3 0    3
6  6 5    6
7  5 6    6
8  8 4    8
9  2 5    5
10 4 3    4
11 5 2    5
12 4 9    9
13 8 5    8
14 1 3    3
15 6 4    6
16 4 9    9
17 2 8    8
18 5 4    5
19 2 4    4
20 4 3    4

Example

 Live Demo

y1<-rnorm(20,5,1)
y2<-rnorm(20,5,1)
y3<-rnorm(20,5,1)
df2<-data.frame(y1,y2,y3)
df2

Output

      y1       y2       y3
1 4.099478 4.230448 3.953806
2 4.053187 4.903182 2.858545
3 3.520492 3.852665 3.435332
4 4.543452 3.686695 2.866868
5 4.515121 5.801454 5.242125
6 3.672339 3.837319 4.184841
7 3.632277 5.192438 4.906935
8 4.964407 6.336687 2.883110
9 4.701393 5.669657 5.752201
10 6.110260 6.242568 3.745174
11 5.344662 6.180198 3.678958
12 4.460156 5.141577 7.177730
13 5.290277 5.068554 6.742803
14 5.574233 3.745219 5.408872
15 4.618122 4.796491 5.568271
16 4.957128 4.904917 3.739419
17 5.006405 3.974164 5.190001
18 5.475608 4.734856 5.781379
19 4.794981 5.272916 4.832726
20 5.165257 6.440599 4.406399

Finding maximum value in each row −

Example

df2$Max<-pmax(df2$y1,df2$y2,df2$y3)
df2

Output

      y1       y2       y3       Max
1 4.099478 4.230448 3.953806 4.230448
2 4.053187 4.903182 2.858545 4.903182
3 3.520492 3.852665 3.435332 3.852665
4 4.543452 3.686695 2.866868 4.543452
5 4.515121 5.801454 5.242125 5.801454
6 3.672339 3.837319 4.184841 4.184841
7 3.632277 5.192438 4.906935 5.192438
8 4.964407 6.336687 2.883110 6.336687
9 4.701393 5.669657 5.752201 5.752201
10 6.110260 6.242568 3.745174 6.242568
11 5.344662 6.180198 3.678958 6.180198
12 4.460156 5.141577 7.177730 7.177730
13 5.290277 5.068554 6.742803 6.742803
14 5.574233 3.745219 5.408872 5.574233
15 4.618122 4.796491 5.568271 5.568271
16 4.957128 4.904917 3.739419 4.957128
17 5.006405 3.974164 5.190001 5.190001
18 5.475608 4.734856 5.781379 5.781379
19 4.794981 5.272916 4.832726 5.272916
20 5.165257 6.440599 4.406399 6.440599

Updated on: 07-Dec-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements