How to Use Min and Max Functions in R?
In this article, we will discuss Min and Max functions in R Programming Language.
Min:
Min function is used to return the minimum value in a vector or the dataframe.
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
# create a vector data = c (23, 4, 56, 21, 34, 56, 73) # get the minimum value print ( min (data)) # get the maximum value print ( max (data)) |
Output:
[1] 4 [1] 73
Example 2:
This example is an R program to get the minimum value and maximum value in the dataframe column.
R
# create a dataframe 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)) # get the minimum value in first column print ( min (data$column1)) # get the minimum value in second column print ( min (data$column2)) # get the minimum value in third column print ( min (data$column3)) # get the maximum value in first column print ( max (data$column1)) # get the maximum value in second column print ( max (data$column2)) # get the maximumvalue in third column print ( max (data$column3)) |
Output:
[1] 4 [1] "deepu" [1] 1.3 [1] 56 [1] "sai" [1] 7.8
Example 3:
This example is an R program to get min and max values across the data frame using fapply() function.
R
# create a dataframe 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)) # get the minimum value across dataframe print ( sapply (data, min)) # get the maximum value across dataframe print ( sapply (data, max)) |
Output:
column1 column2 column3 "4" "deepu" "1.3" column1 column2 column3 "56" "sai" "7.8"
Example 4:
This example is an R program to get the max and min values among columns of the data frame.
R
# create a dataframe 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)) # get the minimum value in multiple # columns of dataframe print ( min ( c (data$column1,data$column2,data$column3))) # get the maximum value in multiple # columns of dataframe print ( max ( c (data$column1,data$column2,data$column3))) |
Output:
[1] "1.3" [1] "sai"
Please Login to comment...