R - max() Function
The R max() function returns largest of all elements present in the argument. The syntax for using this function is given below:
Syntax
max(x1, x2, ..., na.rm = FALSE)
Parameters
x1, x2, ... |
Required. Specify numeric vectors. |
na.rm |
Optional. Specify TRUE to remove NA or NaN values before the computation. Default is FALSE. |
Return Value
Returns largest of all elements present in the argument.
Example:
The example below shows the usage of max() function.
v1 <- c(10, 55, 25, -56, 30, 99) v2 <- c(1, -2, 30, 4, -50) cat("Largest element of v1:", max(v1), "\n") cat("Largest element of v2:", max(v2), "\n") cat("Largest element of v1 and v2:", max(v1, v2), "\n") m <- matrix(c(10, 20, 30, 40, 50, 60), ncol=2) cat("\nThe matrix contains:\n") print(m) cat("Largest element of matrix:", max(m)) cat("\nLargest element along first column:", max(m[,1]))
The output of the above code will be:
Largest element of v1: 99 Largest element of v2: 30 Largest element of v1 and v2: 99 The matrix contains: [,1] [,2] [1,] 10 40 [2,] 20 50 [3,] 30 60 Largest element of matrix: 60 Largest element along first column: 30
Using na.rm parameter
The na.rm parameter can be set TRUE to remove NA or NaN values before the computation.
Example:
Consider the example below to see the usage of na.rm parameter.
v1 <- c(10, 20, 30, NA) v2 <- c(10, 20, 30, NaN) cat("Largest element of v1:", max(v1), "\n") cat("Largest element after removing NA:", max(v1, na.rm=TRUE), "\n") cat("\nLargest element of v2:", max(v2), "\n") cat("Largest element after removing NaN:", max(v2, na.rm=TRUE), "\n")
The output of the above code will be:
Largest element of v1: NA Largest element after removing NA: 30 Largest element of v2: NaN Largest element after removing NaN: 30
❮ R Statistical Functions