which.max & which.min Functions in R (2 Examples)

 

In this article you’ll learn how to locate the first maximum or minimum in a data object using the which.max and which.min functions in R programming.

Table of contents:

If you want to learn more about these contents, keep reading!

 

Creating Exemplifying Data

As a first step, we’ll have to create some data that we can use in the following example syntax:

vec <- c(5, 1, 6, 0, 5, 3, 3, 0, 4, 1)    # Create example vector
vec                                       # Print example vector
#  [1] 5 1 6 0 5 3 3 0 4 1

As you can see based on the previously shown RStudio console output, our example data is a vector object containing ten integers.

 

Example 1: Find Index of First Maximum Using which.max() Function

This example shows how to return the location of the first maximum in a vector object.

For this, we can apply the which.max function to our example vector as shown below:

which.max(vec)                            # Apply which.max function
# [1] 3

The RStudio console has returned the value 3, i.e. the first maximum value in our vector occurs at the third position.

 

Example 2: Find Index of First Minimum Using which.min() Function

This section explains how to determine the location of the index position of the first minimum in a vector.

Consider the following R code and its output:

which.min(vec)                            # Apply which.min function
# [1] 4

The previous output of the RStudio console tells us that the first minimum in our vector is located at the fourth index position.

Note that our example vector contains this minimum value (i.e. 0) at multiple positions. In this tutorial, you can learn how to extract the index positions of all maxima or minima in a data object.

 

Video & Further Resources

Do you need more info on the R programming syntax of this article? Then I recommend having a look at the following video on my YouTube channel. I’m illustrating the R codes of this tutorial in the video.

 

The YouTube video will be added soon.

 

Besides that, you might read the other tutorials on https://statisticsglobe.com/. Some related articles can be found below:

 

At this point you should have learned how to apply the which.max and which.min functions in R programming. Let me know in the comments, in case you have further questions. Furthermore, please subscribe to my email newsletter to get updates on the newest tutorials.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top