R abs() function - calculate absolute value
The R abs() function is used to calculate the absolute value of numeric values.
The absolute value is the non-negative value of a number after removing its sign, and it only concerns the magnitude of the value.
The syntax format of the abs() function is as follows:
abs(x)
Parameter description:
xInput a numeric value or a numeric vector.
Example
# Absolute value of a single numeric value
print(abs(-5))
print(abs(3.14))
# Absolute value of a vector
x <- c(-12, 27, -3, 4.2, -2, 0, -54, 21, -4, 2)
result.abs <- abs(x)
print(result.abs)
print(abs(-5))
print(abs(3.14))
# Absolute value of a vector
x <- c(-12, 27, -3, 4.2, -2, 0, -54, 21, -4, 2)
result.abs <- abs(x)
print(result.abs)
The result of executing the above code is:
[1] 5 [1] 3.14 [1] 12.0 27.0 3.0 4.2 2.0 0.0 54.0 21.0 4.0 2.0
abs() is very commonly used when calculating errors:
Example
# Predicted values and actual values
actual <- c(100, 150, 200, 250, 300)
predicted <- c(98, 155, 195, 260, 310)
# Calculate absolute error
error <- actual - predicted
abs_error <- abs(error)
print(abs_error)
# Calculate mean absolute error (MAE)
mae <- mean(abs_error)
print(paste("Mean absolute error MAE:", mae))
actual <- c(100, 150, 200, 250, 300)
predicted <- c(98, 155, 195, 260, 310)
# Calculate absolute error
error <- actual - predicted
abs_error <- abs(error)
print(abs_error)
# Calculate mean absolute error (MAE)
mae <- mean(abs_error)
print(paste("Mean absolute error MAE:", mae))
The result of executing the above code is:
[1] 2 5 5 10 10 [1] "平均绝对误差 MAE: 6.4"Other extensions
R language examples