R min() and max() Functions - Calculating Minimum and Maximum
The 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 of the min() and max() functions is as follows:
min(x, na.rm = FALSE)
max(x, na.rm = FALSE)
Parameter Description:
-
x Input vector.
-
na.rm A boolean value, default FALSE, sets whether to remove missing values NA.
Example
Create a vector
x
<-
c
(
12
,
27
,
3
,
4.2
,
2
,
2
,
54
,
21
,
4
,
2
)
Calculate the minimum
result.
min
<-
min
(
x
)
(
result.
min
)
Calculate the maximum
result.
max
<-
max
(
x
)
(
result.
max
)
The output of the code above is:
[1] -21
[1] 54
If you want to find the maximum or minimum 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 of all elements
(
max
(
a, b
)
)
Take the larger value at each position
(
pmax
(
a, b
)
)
Take the smaller value at each position
(
pmin
(
a, b
)
)
The output of the code above is:
[1] 35
[1] 10 25 35
[1] 5 20 30
R Language Examples