Find Index of Maximum & Minimum Value of Vector & Data Frame Row in R (2 Examples)
The tutorial will consist of this information:
- Example 1: Determine Index of Maximum & Minimum of Vector
- Example 2: Determine Index of Maximum & Minimum of Data Frame Column
- Video, Further Resources & Summary
Let’s dive into it…
Example 1: Determine Index of Maximum & Minimum of Vector
Example 1 explains how to find the max and min value of a numeric vector in R. First, we need to create an example vector:
vec <- c(3, 1, 8, 3, 2, 5) # Create example vector
Our example vector consists of six numeric vector elements. Now, we can apply the which.max function to find the index of the maximum value…
which.max(vec) # Identify index of max value # 3
…and the which.min function to determine the index of the minimum:
which.min(vec) # Identify index of min value # 2
As you can see based on the previous outputs of the RStudio console, the max value is at position 3 and the min value is located at position 2 of our example vector.
Example 2: Determine Index of Maximum & Minimum of Data Frame Column
We can use a similar R syntax as in Example 1 to determine the row index of the max or min value of a data frame column. First, we have to create some example data:
data <- data.frame(x1 = c(7, 8, 1, 4, 0, 5), # Create example data frame x2 = letters[1:6]) data # Print data to RStudio console # x1 x2 # 1 7 a # 2 8 b # 3 1 c # 4 4 d # 5 0 e # 6 5 f
Our data matrix contains two columns and six rows. Let’s assume that we want to find the index of the rows with the min and max values of our variable x1. Then, we can apply the which.max…
which.max(data$x1) # Apply which.max function to column # 2
…and which.min functions:
which.min(data$x1) # Apply which.min function to column # 5
The highest value of the column x1 is located in row 2 and the lowest value of the column x1 is located in row 5.
Video, Further Resources & Summary
If you need more information on the R programming code of this post, you may have a look at the following video of my YouTube channel. I illustrate the R programming code of this page in the video:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, I can recommend to read the related tutorials of this website. Please find a selection of articles here.
In summary: At this point you should know how to get row-wise minima and maxima in the R programming language. If you have any further questions, let me know in the comments.