R range() Function - Calculating Numeric Range
The R range() function is used to return the minimum and maximum values of elements in a vector.
It returns a vector containing 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:
xInput vector.
na.rmA boolean value, defaulting to FALSE, specifying whether to remove missing values NA.
Example
# Create vector
x <- c(12, 27, 3, 4.2, 2, 2, 54, -21, 4, -2)
# Calculate range
result.range <- range(x)
print(result.range)
# Calculate range (max value minus min value)
print(diff(result.range))
x <- c(12, 27, 3, 4.2, 2, 2, 54, -21, 4, -2)
# Calculate range
result.range <- range(x)
print(result.range)
# Calculate range (max value minus min value)
print(diff(result.range))
Executing the above code produces the following output:
[1] -21 54 [1] 75
range() is particularly useful in plotting, where it can be used to set the axis limits:
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)
print(y_range)
# Use range to extend the axis limits
plot(x, y, type = "o",
ylim = c(y_range[1] - 1, y_range[2] + 1),
main = "Line chart with range()")
x <- 1:10
y <- c(3, 7, 2, 9, 15, 8, 12, 5, 18, 10)
# View the range of y
y_range <- range(y)
print(y_range)
# Use range to extend the axis limits
plot(x, y, type = "o",
ylim = c(y_range[1] - 1, y_range[2] + 1),
main = "Line chart with range()")
Executing the above code produces the following output:
[1] 2 18Other Extensions
R Language Examples