R Basic

Calculating Absolute Value using abs() Function in R

The abs() function calculates the absolute value of a numeric input, returning a non-negative (only positive) value by removing any sign.

Usage of absolute value is high in fields like mathematical computations (mean absolute errors), statistical analysis, and data cleaning in ML tasks.

Syntax

abs(input)

Parameters

Argument Description
input It defines the input object.

It can be anything from a single numeric value (integer, double, or complex), a vector, a matrix, or an array to a data frame or its columns.

Single numeric value

If the input is negative, this method returns a positive number. If the input is already a positive number, it will return the same value as the input.

answer1 <- abs(-21)
answer2 <- abs(19)
answer3 <- abs(-46)

answer1
answer2
answer3

# Output:
# [1] 21
# [1] 19
# [1] 46

Complex numbers

For complex numbers, this method returns the modulus (magnitude).

complex_num <- 3 + 4i

abs(complex_num)

# Output: [1] 5

Numeric vector

It performs element-wise operations on vectors, matrices, or arrays.

vec <- c(11, -21, 19)

abs_vec <- abs(vec)

abs_vec

# [1] 11 21 19

The above output shows that the abs() method preserves the input vector structure. Zero remains unchanged.

Handling missing values

In real-time data, you may encounter a vector or any data structure that has NA values. If this method encounters an NA value, it will return as is.

vec_with_na <- c(-1, NA, 0)

abs_with_na <- abs(vec_with_na)

abs_with_na

# Output: [1] 1 NA 0

Matrix

What if the input is a matrix? Well, it will apply this method individually to each element and return the positive value for each input value while preserving the input structure. 

vec <- c(1, 2, -3, 4, 5, -6, -7, -8, -9)
mtrx <- matrix(vec, nrow = 3, ncol = 3, byrow = TRUE)
mtrx

cat("Absolute value of matrix", "\n")
abs_mtrx <- abs(mtrx)
abs_mtrx

Data frame

df <- data.frame(
  col1 = c(1, -2, -3),
  col2 = c(4, -5, 6),
  col3 = c(-7, 8, -9)
)

df

print("After calculating the absolute value of data frame")

df_abs <- abs(df)

df_abs

Output

Specific data frame column

Sometimes, you need to find the absolute value of a specific column and not the whole data frame.

df <- data.frame(
  col1 = c(1, -2, -3),
  col2 = c(4, -5, 6),
  col3 = c(-7, 8, -9)
)
df

print("After calculating the absolute value of data frame")
df_col_abs <- df
df_col_abs$col3 <- abs(df_col_abs$col3)
df_col_abs

Absolute difference between two values

diff <- 19 - 21

diff_abs <- abs(diff)

diff_abs

Output

[1] 2

Errors

Case 1

If you encounter the error Error in abs(“Rlang”) : non-numeric argument to mathematical function, that means you passed a character vector or string to the abs() method.

abs("Rlang")

# Output: Error in abs("Rlang") : non-numeric argument to mathematical function

Don’t pass the character vector to a numeric function. This will prevent the above error from occurring.

Case 2

Error in Math.factor(x) : ‘abs’ not meaningful for factors typically occurs when you are trying to apply a mathematical function (like abs()) to a factor variable.

Factor variables are categorical variables that take on a limited number of different values; they aren’t numerical and, therefore, can’t be used in most mathematical operations.

x <- factor(c("1", "2", "3"))

abs(x)

Error in Math.factor(x) : ‘abs’ not meaningful for factors

To fix this error, you must “ensure that the variable you are passing to abs() (or any other mathematical function) is numerical”. If the variable is stored as a factor but represents numbers (e.g., “1”, “2”, “3”), you can convert it to numeric with the as.numeric() function.

x <- factor(c("-1", "2", "-3"))

abs(as.numeric(as.character(x)))

# Output: [1] 1 2 3

Real-World Application: Mean Absolute Error (MAE)

To calculate Mean Absolute Error, we need to calculate the average of the absolute differences between actual and predicted values.

actual <- c(10, 20, 30, 40)
predicted <- c(12, 18, 33, 37)

mae <- mean(abs(actual - predicted))

mae

# Output: 2.5

That’s all!

Recent Posts

Calculating Natural Log using log() Function in R

The log() function calculates the natural logarithm (base e) of a numeric vector. By default,…

4 days ago

Dollar Sign ($ Operator) in R

In R, you can use the dollar sign ($ operator)  to access elements (columns) of…

3 weeks ago

Printing an Output of a Program in R

When working with R in an interactive mode, you don't need to use any functions…

1 month ago

How to Calculate Variance in R

To calculate the sample variance (measurement of spreading) in R, you should use the built-in…

1 month ago

tryCatch() Function in R

The tryCatch() function acts as a mechanism for handling errors and other conditions (like warnings…

1 month ago

R grep(): Finding a Position of Matched Pattern

The grep() function in R  searches for matches to a pattern within a character vector.…

1 month ago