abs()
abs(x) numeric · Added in v1.0 · Updated March 13, 2026 · Base Functions The abs() function in R computes the absolute value of a numeric or complex vector. Absolute value represents the distance of a number from zero on the number line, always returning a non-negative result. This makes it essential for calculating distances, measuring errors, and any scenario where only the magnitude matters, not the direction.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x | numeric or complex vector | Required | A numeric or complex vector for which to compute absolute values |
Return Value
Returns a numeric vector of the same length as x, containing the absolute values. For complex numbers, abs() returns the modulus (magnitude), calculated as sqrt(real^2 + imag^2).
Examples
Basic Usage
# Absolute value of a positive number
abs(5)
# [1] 5
# Absolute value of a negative number
abs(-5)
# [1] 5
# Absolute value of zero
abs(0)
# [1] 0
# Absolute value of a numeric vector
abs(c(-3, 0, 3, -7))
# [1] 3 0 3 7
Working with Data Frames
# Calculate differences from a baseline
measurements <- data.frame(
value = c(10, -5, 3, -8, 0, 12)
)
baseline <- 5
# Get absolute deviations from baseline
abs(measurements$value - baseline)
# [1] 5 0 2 3 5 7
# Find the maximum absolute deviation
max(abs(measurements$value - baseline))
# [1] 7
Working with Complex Numbers
# Absolute value (modulus) of complex numbers
abs(3 + 4i)
# [1] 5
abs(1 + 1i)
# [1] 1.414214
abs(-2 - 2i)
# [1] 2.828427
Practical Applications
# Calculate prediction errors
actual <- c(100, 85, 120, 90, 105)
predicted <- c(95, 90, 115, 88, 100)
# Mean Absolute Error (MAE)
mean(abs(actual - predicted))
# [1] 4
# Find values within tolerance
values <- c(1.0, 1.1, 0.9, 1.3, 0.95)
target <- 1.0
tolerance <- 0.1
values[abs(values - target) <= tolerance]
# [1] 1.0 0.9 0.95
Vectorized Operations
# abs() is vectorized - works element-wise on vectors
errors <- c(-10.5, 3.2, -0.5, 8.1, -2.9)
abs_errors <- abs(errors)
abs_errors
# [1] 10.5 3.2 0.5 8.1 2.9
# Use with sapply for list processing
data_list <- list(a = -5, b = 10, c = -3, d = 0)
sapply(data_list, abs)
# a b c d
# 5 10 3 0
Handling NA Values
# abs() propagates NA values
abs(c(1, -2, NA, 4, -5))
# [1] 1 2 NA 4 5
# Use is.na() to check for NA before processing
x <- c(1, -2, NA, 4, -5)
ifelse(is.na(x), NA, abs(x))
# [1] 1 2 NA 4 5
Common Use Cases
The abs() function is frequently used in statistical and data analysis workflows. Some common applications include:
-
Error Measurement: Calculate Mean Absolute Error (MAE) or Mean Absolute Percentage Error (MAPE) to evaluate model performance.
-
Distance Calculations: When working with geographic coordinates or any spatial data, absolute values help compute distances regardless of direction.
-
Financial Analysis: Calculate absolute returns, deviations from targets, or price changes.
-
Signal Processing: Work with signals and time series where only the magnitude of deviations matters.