Skip to content
Related Articles

Related Articles

Improve Article

Return Column Name of Largest Value for Each Row in R DataFrame

  • Last Updated : 23 Sep, 2021

In this article, we will discuss how to return column names of the largest value for each row in DataFrame in R Programming Language.

Example:

 Column1Column2Column3Max column
Row1200Column1 , Because,  Column2 value and Column 3 value is less than Column1
Row2435Column3 , Because,  Column2 value and Column 1 value is less than Column3
Row31066Column1 , Because,  Column2 value and Column 3 value is less than Column1
Row4954Column1 , Because,  Column2 value and Column 3 value is less than Column1
Row5793Column2 , Because,  Column1 value and Column 3 value is less than Column2

So For this implementation we will use colnames() and max.col() functions

Syntax:

colnames(dataframe)[max.col(dataframe)]



Here, 

  • colnames() is used to get the column names
  • max.col() is used to return the maximum column name of the dataframe

Example: R program to get the largest column name in all rows

R




# create  a dataframe with 3 columns and 3 rows
data = data.frame(subject1=c(91, 62, 93),
                  subject2=c(98, 79, 70),
                  subject3=c(100, 78, 98))
  
  
# get the largest column name in each row
print(colnames(data)[max.col(data)])

Output:

[1] "subject3" "subject2" "subject3"

Example: R program to get the largest column name in all rows

R




# create  a dataframe with 4 columns and 3 rows
data = data.frame(subject1=c(91, 62, 93, 56, 78),
                  subject2=c(98, 79, 70, 56, 78),
                  subject3=c(100, 78, 98, 56, 71))
  
# get the largest column name in each row
print(colnames(data)[max.col(data)])

Output:

[1] "subject3" "subject1" "subject3" "subject1" "subject2"



My Personal Notes arrow_drop_up
Recommended Articles
Page :