max() function in detail
max() Function in R Language
The max() function in R is used to identify the largest element in a given object. This object can be a vector, list, matrix, data frame, etc.
Syntax
max(object, na.rm)
Parameters
- object: Any R object such as a vector, matrix, list, or data frame.
- na.rm: A logical value (
TRUEorFALSE) that determines whether to ignoreNAvalues.
Example 1: Finding the Maximum Element in Vectors
# Creating vectors
vector1 <- c(12, 25, 8, 14, 19)
vector2 <- c(5, NA, 17, 4, 10)
# Finding the maximum element
max(vector1) # Without NA
max(vector2, na.rm = FALSE) # Includes NA
max(vector2, na.rm = TRUE) # Excludes NA
Output:
[1] 25
[1] NA
[1] 17
Example 2: Finding the Maximum Element in a Matrix
# Creating a matrix
matrix_data <- matrix(1:12, nrow = 3, ncol = 4)
print(matrix_data)
# Finding the maximum element
max(matrix_data)
Output:
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
[1] 12
Leave a Reply