This blog explains the way to find the row index that contains the maximum value using R Language, along with illustrating a basic example.
Introduction
To find the row having the max index value in a dataframe can achieved using the which.max() function. The which.max() function is a function that helps to identify the index of the very first occurrence of the maximum value in a vector or array. This function is defined in the R’s base package.
Syntax
which.max(dataframe_name$columnname) )
Where “$” is utilized to access a particular column of a dataframe. This function evaluates the element to find the max value.
Return Type
This function returns the index of the very first element that contains the maximum value in x.
The which.max() Function works on numeric, character, and logical vectors, and does not handle NA values automatically. To handle this, the ifelse() or na.omit() function needs to be defined explicitly.
To find the maximum values across rows or columns in the data frames or matrices functions like apply() or which() need to be combined with the which.max() function.
Example
# vector 1
data1=c("Alices","John","Mary","Smith","Emily")
# vector 2
data2=c(586,783,379,797,989)
# creating a dataframe with names and salary
final <- data.frame(names=data1,salary=data2)
print(final)
# display the maximum value index in a dataframe
print(paste("highest Salary is at index: ",which.max(final$salary)))
Output
|
Names |
Salary |
1 | Alices | 586 |
2 | John | 783 |
3 | Mary | 379 |
4 | Smith | 797 |
5 | Emily | 989 |
[1] “highest Salary is at index: 5”
Conclusion
The which.max() function in R is a simple, efficient, and versatile function to find the index of the first occurrence of the maximum value in an array or vector. This function is mainly used to find the position of the ma value in numeric, character, or logical vectors. If you are interested in learning more about R, then check out our R Programming Course.
FAQs
What does which.max() function do?
This function provides the index for the first occurrence of the maximum value in an array or a vector. It accepts the numeric, character, or any logical vector.
How is which.max() different from max()?
The which.max() function returns the index for the first occurrence of the maximum value in an array or a vector, whereas the max() function returns the maximum value from the set of values.
How the which.max() deals with the vector containing NA values?
This function returns NA for the vector containing NA values. Set the na.rm to a TRUE option with the max() function or preprocess the data, to handle this issue.
What should the which.max() return if handling the multiple maximum values?
The which.max() function only returns the index of the first occurrence of the maximum value.