max and min Functions in R (2 Examples)
The following R code shows how to apply the max and min functions in the R programming language.
Apply max and min Functions
Example data:
vec <- c(2, 1, 5, 2, 8, 3) # Create example vector |
vec <- c(2, 1, 5, 2, 8, 3) # Create example vector
Apply max function:
max(vec) # Return maximum of vector # 8 |
max(vec) # Return maximum of vector # 8
Apply min function:
min(vec) # Return minimum of vector # 1 |
min(vec) # Return minimum of vector # 1
Remove NA Values within max Function
Example data:
vec2 <- c(vec, NA) # Create vector with NA |
vec2 <- c(vec, NA) # Create vector with NA
Apply max function:
max(vec2) # max function returns NA # NA |
max(vec2) # max function returns NA # NA
Since our example vector contains an NA value, the max function also returns NA. We can apply the na.rm argument to return our true maximum:
max(vec2, na.rm = TRUE) # Use na.rm argument # 8 |
max(vec2, na.rm = TRUE) # Use na.rm argument # 8
Video Example
This video shows further examples for the computation of maxima and minima in R: