How to Use min() and max() in R
Last Updated :
06 Jun, 2023
In this article, we will discuss Min and Max functions in R Programming Language.
Min:
The Min function is used to return the minimum value in a vector or the data frame.
Syntax:
In a vector:
min(vector_name)
In a dataframe with in a column:
min(dataframe$column_name)
In a dataframe multiple columns:
min(c(dataframe$column1,dataframe$column2,......,dataframe$columnn))
In a whole dataframe across all columns
sapply(dataframe,min)
Max:
Max function is used to return the maximum value in a vector or the data frame.
Syntax:
In a vector:
max(vector_name)
In a dataframe with in a column:
max(dataframe$column_name)
In a dataframe multiple columns:
max(c(dataframe$column1,dataframe$column2,......,dataframe$columnn))
In a whole dataframe across all columns
sapply(dataframe,max)
Example 1:
This example is an R program to get minimum and maximum values in the vector.
R
data = c (23, 4, 56, 21, 34, 56, 73)
print ( min (data))
print ( max (data))
|
Output:
[1] 4
[1] 73
Example 2:
This example is an R program to get the minimum and maximum values in the data frame column.
R
data= data.frame (column1= c (23,4,56,21),
column2= c ( "sai" , "deepu" , "ram" , "govind" ),
column3= c (1.3,4.6,7.8,6.3))
print ( min (data$column1))
print ( min (data$column2))
print ( min (data$column3))
print ( max (data$column1))
print ( max (data$column2))
print ( max (data$column3))
|
Output:
[1] 4
[1] "deepu"
[1] 1.3
[1] 56
[1] "sai"
[1] 7.8
The min() and max() function in R compare character values according to their ASCII codes when applied to character data.
Each character in the English language has a specific number thanks to the ASCII (American Standard Code for Information Interchange) encoding system. A character with the shortest ASCII code value is returned by the min() function, while a character with the highest ASCII code value is returned by the max() function.
Example 3:
This example is an R program to get min and max values across the data frame using fapply() function.
R
data = data.frame (column1= c (23, 4, 56, 21),
column2= c ( "sai" , "deepu" , "ram" , "govind" ),
column3= c (1.3, 4.6, 7.8, 6.3))
print ( sapply (data, min))
print ( sapply (data, max))
|
Output:
column1 column2 column3
"4" "deepu" "1.3"
column1 column2 column3
"56" "sai" "7.8"
Example 4:
Max() and Min() function in R with NA values.
R
x <- c (2, 4, 1, NA , 3)
max (x)
min (x)
|
Output:
> max(x)
[1] NA
> min(x)
[1] NA
To get the maximum or minimum of the non-missing values, however, and to eliminate missing values from the computation, you can use the na.rm parameter. The calculation will not include NA values if na.rm is set to TRUE. For instance:
R
max (x, na.rm = TRUE )
min (x, na.rm = TRUE )
|
Output:
[1] 4
[1] 1
Share your thoughts in the comments
Please Login to comment...