R range() Function - Computing the Numeric Range
The R range() function is used to return the minimum and maximum values of elements in a vector.
It returns a vector of two values at once, which is more convenient than calling min() and max() separately.
The syntax of the range() function is as follows:
range(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
)
Compute the range
result.
range
<-
range
(
x
)
(
result.
range
)
Compute the span (maximum minus minimum)
(
diff
(
result.
range
)
)
The output of the code above is:
[1] -21 54
[1] 75
range() is especially useful when plotting, for setting the range of axes:
Example
Create data
x
<-
1
:
10
y
<-
c
(
3
,
7
,
2
,
9
,
15
,
8
,
12
,
5
,
18
,
10
)
View the range of y
y_range
<-
range
(
y
)
(
y_range
)
Use range to extend the axis range
plot
(
x, y, type
=
"o"
,
ylim
=
c
(
y_range
[
1
]
1
, y_range
[
2
]
1
)
,
main
=
"Line plot with range()"
)
The output of the code above is:
[1] 2 18
R Language Examples