How to create a column with column name for maximum value in each row of an R data frame?


To create a column with column name for maximum value in each row of an R data frame, we can follow the below steps −

  • First of all, create a data frame.

  • Then, use mutate function of dplyr package along with max.col function to create a column with column name for maximum value in each row of an R data frame.

Example

Create the data frame

Let’s create a data frame as shown below −

x<-sample(1:50,25)
y<-sample(1:50,25)
z<-sample(1:50,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   9 17 21
2  20 43 27
3  50 33 30
4  25  8 18
5  44  5 20
6  34 41 42
7  23 15 12
8   2 23 35
9  43 27  5
10 29 12 47
11 42 19 15
12 15 28 32
13 13 36 39
14 10 50 14
15 19 11 45
16  5 24 37
17 48  2 11
18 36 25 10
19 31 10 48
20 38 49 36
21 11 46  4
22 41  1 44
23  7 26 46
24 22 34  9
25 16 45  3

Create a column with column name for maximum value in each row

Using mutate function of dplyr package along with max.col function to create a column with column name for maximum value in each row of data frame df −

x<-sample(1:50,25)
y<-sample(1:50,25)
z<-sample(1:50,25)
df<-data.frame(x,y,z)
library(dplyr)
df %>% mutate(Class=names(.)[max.col(.)])

Output

    x  y z  Class
1   9 17 21 z
2  20 43 27 y
3  50 33 30 x
4  25  8 18 x
5  44  5 20 x
6  34 41 42 z
7  23 15 12 x
8   2 23 35 z
9  43 27  5 x
10 29 12 47 z
11 42 19 15 x
12 15 28 32 z
13 13 36 39 z
14 10 50 14 y
15 19 11 45 z
16  5 24 37 z
17 48  2 11 x
18 36 25 10 x
19 31 10 48 z
20 38 49 36 y
21 11 46  4 y
22 41  1 44 z
23  7 26 46 z
24 22 34  9 y
25 16 45  3 y

Updated on: 15-Nov-2021

914 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements