How to Calculate MAE in R (original) (raw)

Last Updated : 23 Jul, 2025

Mean Absolute Error (MAE) is a metric used to measure the accuracy of a model by calculating the average of the absolute differences between the observed (actual) values and the predicted values. It is a commonly used metric in regression analysis and model evaluation because it gives a clear understanding of how far off a model's predictions are from the actual values. A lower MAE indicates a more accurate model, while a higher MAE suggests larger discrepancies between predictions and actual values.

Formula for MAE

MAE = \frac{1}{n} \sum_{i=1}^{n} |y_i - x_i|

**Where:

Methods to Calculate MAE in R

We will discuss the different methods to calculate Mean Absolute Error (MAE) in R programming language.

1. Using the Actual Formula

In this method, we manually calculate the Mean Absolute Error (MAE) by applying the formula for the absolute differences between the actual and predicted values. This method involves using a loop to iterate over the vectors of actual and predicted values, summing the absolute differences, and then dividing by the number of observations.

actual = c(8,9,6,1,4,8,6,4,5,6) calculated = c(9,6,4,8,4,1,2,3,9,6) n = 10 sum = 0

for (i in 1:n){ sum = abs(actual[i] - calculated[i]) + sum }

error = sum / n

error

`

**Output:

[1] 2.9

2. Using the mae() Function from the Metrics Package

This method simplifies the calculation by using the mae() function from the Metrics package, which directly computes the Mean Absolute Error for given vectors of actual and predicted values.

install.packages('Metrics') library(Metrics)

actual = c(8,9,6,1,4,8,6,4,5,6) calculated = c(9,6,4,8,4,1,2,3,9,6)

mae(actual, calculated)

`

**Output:

[1] 2.9

3. Calculating MAE for a Regression Model

In this method, we calculate the MAE for a regression model. First, a regression model is built using a data frame , and then the predicted values are compared to the actual values to calculate the MAE. This method helps in evaluating the performance of the model.

install.packages('Metrics') library(Metrics)

gfg_df <- data.frame(x1=c(4,8,9,4,1,8,9,4,1,6), x2=c(1,3,2,8,9,9,6,7,4,1), y=c(8,5,1,3,2,4,1,6,2,5))

model <- lm(y ~ x1 + x2, data = gfg_df)

mae(gfg_df$y, predict(model))

`

**Output:

[1] 1.782963

These three methods provide different approaches to calculating the Mean Absolute Error (MAE) in R, from manual calculation to using built-in functions for easier computation, and evaluating model performance in regression analysis.