In this article, you will learn how to use min and max in R. I’m going to explain both functions in the same tutorial, since the R syntax of the two functions is exactly the same.
Basic R Syntax:
max(x)min(x)
The R max function returns the maximum value of a vector or column.
The R min function returns the minimum value of a vector or column.
The basic R code for the max and min functions is shown above. In the following R tutorial, I’m going to show you eight examples for the application of max and min in the R programming language.
Let’s dive into it…
Example 1: Apply max & min to Vector in R
The most basic usage of max and min is their application to a numeric vector. Let’s create an example vector first:
x1 <- c(4, 1, - 50, 20, 8) # Create example vector
Our example vector consists of five numbers, stored in the data object x1. Now, let’s compute the maximum and minimum of this vector.
The maximum can be computed with the following R code:
max(x1) # Apply max to vector# 20
As you can see in the RStudio console, the maximum of our vector is 20.
The same code works for the min function:
min(x1) # Apply min to vector# -50
The minimum value of our vector is – 50.
By the way: I have also recorded a video containing Examples 1 and 2 of this tutorial. You can check out the video tutorial here:
As you have seen in the video, there might occur complications when we have NA values. You can find the code of the second example of the video in the following…
Example 2: Vector with NA Value
A problem can occur, when your data contains NA values (i.e. missing data). For the second example, let’s add some missing data to our example vector:
x2 <- c(x1, NA) # Create example vector with NAx2 # Print vector to RStudio console# 4 1 -50 20 8 NA
Our new example vector looks exactly as in Example 1, but this time with an NA value at the end. Let’s see what happens when we apply max and min as before:
max(x2) # max returns NA# NA
The max function returns NA…
min(x2) # min also returns NA# NA
…and the min function does the same.
But don’t worry, there is an easy solution! Just specify the option na.rm = TRUE within the max and min functions:
max(x2, na.rm = TRUE) # Specify na.rm = TRUE# 20
As you can see, by using na.rm = TRUE we get the same maximum…
min(x2, na.rm = TRUE) # Specify na.rm = TRUE# -50
…and minimum as in Example 1.
Perfect!
But what if we want to apply max and min to a column of a data frame? You guessed it, that’s what I’m going to show you next.
Example 3: max() & min() of Column
For the next example, I’m going to use the mtcars data set. The data can be loaded with the following R code:
data("mtcars") # Load mtcars data in RStudio
Let’s have a look at the data:
head(mtcars) # First 6 rows of mtcars data frame
Table 1: The mtcars Data as Example data.frame for the Application of max() and min().
Each row of the mtcars data set consists of one car and the columns of the data contain different information on each car (mpg = miles per gallon; cyl = cylinder; and so on…).
If we want to calculate the maximum and minimum of one column, we can apply the max and min algorithms to this column with the name of the data, the $-sign, and the name of the column. Let’s do this in practice:
max(mtcars$mpg) # Compute max of column mpg# 33.9
Same for min:
min(mtcars$mpg) # Compute max of column mpg# 10.4
The maximum of the column mpg of the mtcars data frame is 33.9 and the minimum is 10.4.
Let’s automatize this code…
Example 4: Maxima & Minima Across All Columns
You might be interested in the maxima and minima of all the columns of your data matrix. Of cause, you could apply the max and min R functions to each of the columns one by one. However, the sapply function provides a much smoother and automatized way to calculate all maxima and minima with one line of code.
The maxima across all columns can be computed as follows…
sapply(mtcars, max) # Compute max of all columns# mpg cyl disp hp drat wt qsec vs am gear carb# 33.900 8.000 472.000 335.000 4.930 5.424 22.900 1.000 1.000 5.000 8.000
…and the minima across all columns can be computed as follows:
sapply(mtcars, min) # Compute min of all columns# mpg cyl disp hp drat wt qsec vs am gear carb# 10.400 4.000 71.100 52.000 2.760 1.513 14.500 0.000 0.000 3.000 1.000
So, what if you don’t care about a single column. You want to know the maximum and minimum of the whole data set? So be it…
Example 5: Global max & min of Data Frame
The computation of the global max and min of a data table is quite easy. Just apply max and min as we did in the previous examples – but this time insert the name of the whole data frame between the parentheses:
max(mtcars) # Apply max algorithm to whole data.frame# 472
The global maximum of mtcars is 472…
min(mtcars) # Apply min algorithm to whole data.frame# 0
…and the global minimum is zero.
By the way, if you compare these results with the results of Example 4, you can see that the global maximum of 472 is in the column disp, and the global minimum of zero is in both vs and am.
Example 6: max & min Between Two Columns
Another situation where max and min can be helpful is when you want to know the max and min between two columns or vectors.
Let’s assume that we want to know the maximum and minimum value of the columns mpg and cyl. We can calculate that with the following R codes for max…
max(c(mtcars$mpg, mtcars$cyl)) # Max between two columns / vectors# 33.9
…and with the following line of command for min:
min(c(mtcars$mpg, mtcars$cyl)) # Min between two columns / vectors# 4
OK looks good. I think that’s enough for columns – but what about maxima and minima of rows?
Example 7: Maximum & Minimum of Row
Sure, the typical application of max and min is to columns. But sometimes it might be useful to know the maximum or minimum of a row. We can compute that with the following R code:
max(mtcars[5,]) # Compute max of one row# 360
The maximum of row number five is 360…
min(mtcars[5,]) # Compute min of one row# 0
… and the minimum is zero.
Note: You can replace the number 5 with any row number you want.
You think that has proven the flexibility of min and max? Wait for the next example…
Example 8: Maximum & Minimum of Character String
The maximum and minimum is useful for numbers and that’s it, correct?
Nope, that’s wrong!
We can also use max and min to determine minima or maxima of strings in an alphabetic order. We can do that by simply inserting a character vector (or column or row) between the parentheses of the max and min functions.
As in the examples before, let’s start with some example data:
x_char <- c("hello", # Create character vector "R is nice", "max and min functions are awesome", "aaaaaa")
Our example vector contains some random words and phrases. If we want to check, which of these strings is the last one in the alphabet, we can apply the max function…
max(x_char) # Apply max to character vector# "R is nice"
…and if we want to examine, which string is the first in alphabetic order, we can use the R min function…
min(x_char) # Apply min to character vector# aaaaaa
Obviously, in this group of strings it’s aaaaaa.
Video: max, min & Similar Functions
In this tutorial, I showed you several ways how to use max and min to find the highest and lowest values in R. However, there are many R functions that can be used in a similar fashion. If you want to learn more about that, I can recommend the following YouTube video of the BIO-RESEARCH channel.
Further Reading
- summary Function in R
- NA Values in R
- List of R Functions
- The R Programming Language
18 Comments. Leave new
Zara
December 2, 2021 1:30 am
This is super helpful. Thank you.
ReplyJoachim
December 2, 2021 8:16 am
That’s great to hear! Thank you Zara 🙂
Reply
nadia
January 20, 2022 11:47 pm
how r dr.
Reply
can i ask how to make a loop for the matrix to find the minimum value from all each row
I have nrow=r=30, ncol=m=15 , n=450 and print all resultJoachim
January 21, 2022 7:18 am
ReplyHey Nadia,
You don’t need a loop for this. You can use the apply function instead:
set.seed(25687) # Create example matrixmat <- matrix(runif(30 * 15), nrow = 30, ncol = 15)apply(mat, 1, min) # Return min of each row
Regards,
Joachim
naida
January 21, 2022 10:20 pm
Replyn=450
r=30
m=15
x=rweibull(n,scale=1.005, shape=1)
y=matrix(data = NA, nrow = m, ncol =r, byrow = FALSE, dimnames = NULL)
y<-matrix(x, nrow=m, ncol=r)
y
z<-c()for(j in 1:10){
for(i in 1:m){
z[i] =min(y[i,])
}
M[j]=mean(z)
f[j]=(1/(2*((r+1)*M[j]))
}
z
M[j]
ffhat1=mean(f)
fhat1this is my code but didn't work, i don't know whats I should do to run
Joachim
January 24, 2022 11:35 am
ReplyHey,
Have you tried to run the code I suggested above? I.e.
apply(y, 1, min)
Regards,
Joachim
Sanjjith
June 11, 2022 4:17 am
Explain with better examples..
ReplyJoachim
June 13, 2022 7:10 am
ReplyHey Sanjjith,
Could you explain what criteria such a “better example” should follow?
Regards,
Joachim
Alberto
July 16, 2022 6:22 pm
Thank you very much! Very helpful and with clear examples.
ReplyJoachim
July 17, 2022 7:43 am
ReplyThanks a lot Alberto, this is great to hear! 🙂
Regards,
Joachim
Fatma
July 23, 2022 7:19 am
hello dr. agreat effort that we appretiate.
Reply
how can i creat a functions calculate minimume and maximum values on matrix or data frame without using the inbuilt functions.Joachim
July 25, 2022 7:18 am
ReplyHey Fatma,
Is there a specific reason why you don’t want to use the max and min functions?
Regards,
Joachim
C
November 12, 2022 8:46 am
Thanks for all your help!!!
ReplyMatthias (Statistics Globe)
November 14, 2022 11:20 am
ReplyThanks for the kind response, glad to hear that you find our tutorials helpful!
Regards,
Matthias (Statistics Globe)
kaiz
February 17, 2023 11:35 am
Write a user defined function in R that can find the maximum value in a numerical vector containing 1 million values
ReplyCansu (Statistics Globe)
February 17, 2023 12:32 pm
ReplyHello Ian,
If you want to learn more about user-defined functions in R, you can check the following page: https://www.dataquest.io/blog/write-functions-in-r/. To the best of my knowledge, we do not have such a tutorial.
Regards,
Cansu
Jéssica Mariano
March 9, 2024 11:38 pm
Hello, I want to know how to filter the max and min of a database with many rows where I need to filter by category. For example, I want to know if in a region/column, what is the maximum sea level for each month. Can you help me with that?
ReplyJoachim (Statistics Globe)
March 12, 2024 8:52 am
ReplyHey Jéssica,
Thank you for your comment!
Regarding your question, please take a look here.
Regards,
Joachim
Leave a Reply
I’m Joachim Schork. On this website, I provide statistics tutorials as well as code in Python and R programming.
Statistics Globe Newsletter
Related Tutorials