R min() and max() functions - calculate minimum and maximum values
R min() and max() functions are used to calculate the minimum and maximum values of elements in a vector, respectively.
These two functions are very commonly used in data exploration and outlier detection.
The syntax format of the min() and max() functions is as follows:
min(x, na.rm = FALSE) max(x, na.rm = FALSE)
Parameter description:
xInput vector.
na.rmBoolean value, default is FALSE, sets whether to remove missing values NA.
Example
# Create vector
x <- c(12, 27, 3, 4.2, 2, 2, 54, -21, 4, -2)
# Calculate minimum value
result.min <- min(x)
print(result.min)
# Calculate maximum value
result.max <- max(x)
print(result.max)
x <- c(12, 27, 3, 4.2, 2, 2, 54, -21, 4, -2)
# Calculate minimum value
result.min <- min(x)
print(result.min)
# Calculate maximum value
result.max <- max(x)
print(result.max)
The output result after executing the above code is:
[1] -21 [1] 54
If you want to find the maximum or minimum value among multiple vectors, you can use pmax() and pmin() for element-wise comparison:
Example
# Two vectors
a <- c(10, 20, 30)
b <- c(5, 25, 35)
# Find the maximum value of all elements
print(max(a, b))
# Take the larger value position by position
print(pmax(a, b))
# Take the smaller value position by position
print(pmin(a, b))
a <- c(10, 20, 30)
b <- c(5, 25, 35)
# Find the maximum value of all elements
print(max(a, b))
# Take the larger value position by position
print(pmax(a, b))
# Take the smaller value position by position
print(pmin(a, b))
The output result after executing the above code is:
[1] 35 [1] 10 25 35 [1] 5 20 30Other extensions
R language examples