Return Column Name of Largest Value for Each Row in R DataFrame
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:
Column1 | Column2 | Column3 | Max column | |
---|---|---|---|---|
Row1 | 2 | 0 | 0 | Column1 , Because, Column2 value and Column 3 value is less than Column1 |
Row2 | 4 | 3 | 5 | Column3 , Because, Column2 value and Column 1 value is less than Column3 |
Row3 | 10 | 6 | 6 | Column1 , Because, Column2 value and Column 3 value is less than Column1 |
Row4 | 9 | 5 | 4 | Column1 , Because, Column2 value and Column 3 value is less than Column1 |
Row5 | 7 | 9 | 3 | Column2 , 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"
Please Login to comment...