# R max() Function

R max() function is used to find the maximum value of a vector or data frame. For example,  if you have vec <- c(21, 19, 11, 2, 18, 3), then max(vec) will return 21.

This function can be used with any data type that is coercible to numeric, including logical vectors where TRUE is treated as 1 and FALSE as 0.

## Syntax

``max(input, na.rm = FALSE)``

## Parameters

1. input: It is a  Vector or a data frame.
2. na.rm: It removes the NA values; if it mentions FALSE, it considers NA, or if it mentioned TRUE, it removes NA from the vector or a data frame.

## Return Value

It returns the maximum value of a vector or data frame.

## Example 1: Finding the maximum value of a vector

``````rv <- c(19, 21, -20, -46, 29)

cat("The maximum value of thev vector is:", max(rv))``````

Output

``The maximum value of thev vector is: 29``

You can see from the vector that mathematically, the maximum value is 29, and we get the same output.

## Example 2: Ignoring NA values

If you add the NA value as missing data to the vector, it will return the NA value as a maximum value because it is not what the NA value is.

``````rv <- c(19, 21, -20, NA, 29)

cat("The maximum value of thev vector is:", max(rv))``````

Output

``The maximum value of thev vector is: NA``

But don’t worry, and there is an easy solution! Just specify the option na.rm = TRUE within the max() function.

``````rv <- c(19, 21, -20, NA, 29)

cat("The maximum value of thev vector is:", max(rv, na.rm = TRUE))``````

Output

``The maximum value of thev vector is: 29``

## Example 3: Using max() function on data frame

``````df <- data.frame(
"col1" = c(21, 19, 11),
"col2" = c(18, 46, 10),
"col3" = c(5, 15, 25)
)

max(df)``````

Output

``````[1] 46
``````

## Example 4: Finding the maximum value between two columns

``````df <- data.frame(
"col1" = c(21, 19, 11),
"col2" = c(18, 46, 10),
"col3" = c(5, 15, 25)
)

max(c(df\$col1, df\$col3))
``````

Output

``[1] 25``

## Example 5: Finding the Maximum of the row

``````df <- data.frame(
"col1" = c(21, 19, 11),
"col2" = c(18, 46, 10),
"col3" = c(5, 15, 25)
)

max(df[2, ])
``````

Output

``````[1] 46
``````

## Example 6: Finding a global max value of a specific column of a dataset

``````data(ChickWeight)
val <- max(ChickWeight\$weight)
cat("The maximum value of weight column is:", val)
``````

Output

``The maximum value of weight column is: 373``

That means the maximum weight of the ChickWeight dataset is 373.

## Example 7: Finding the maximum global value of the dataset

``````data(mtcars)
max(mtcars)``````

Output

``[1] 472``

That’s it.