How to Calculate Mean Absolute Percentage Error (MAPE) in R

How to Calculate MAPE in R, when want to measure the forecasting accuracy of a model the solution is MAPE.

MAPE stands for mean absolute percentage error.

The mathematical formula to calculate MAPE is:

MAPE = (1/n) * Σ(|Original – Predicted| / |Original|) * 100

where:

Σ –indicates the “sum”

n – indicates the sample size

actual – indicates the actual data value

forecast – indicates the forecasted data value

What are the Nonparametric tests? » Why, When and Methods »

Why MAPE?

MAPE is one of the easiest methods and easy to infer and explain. Suppose MAPE value of a particular model is 5% indicate that the average difference between the predicted value and the original value is 5%.

In this tutorial, we are going to cover two different approaches used to calculate MAPE in R.

Data Analysis in R pdf tools & pdftk » Read, Merge, Split, Attach »

Approach 1: Function

Let’s create a data frame with actual and predicted values.

create a dataset

data <- data.frame(actual=c(44, 47, 34, 47, 58, 48, 46, 53, 32, 37, 26, 24),
forecast=c(44, 40, 46, 43, 46, 58, 45, 44, 53, 30, 32, 23))

View  the dataset

data
    actual forecast
1      44       44
2      47       40
3      34       46
4      47       43
5      58       46
6      48       58
7      46       45
8      53       44
9      32       53
10     37       30
11     26       32
12     24       23

How to Calculate Partial Correlation coefficient in R-Quick Guide »

Now we can calculate MAPE in R based on our own function.

We can make use of the following function for MAPE calculation.

mean(abs((data$actual-data$forecast)/data$actual)) * 100
[1] 19.26366

For the current model, the MAPE value is 19.26, It’s indicated that the average absolute difference between the predicted value and the original value is 19.26%.

Intraclass Correlation Coefficient in R-Quick Guide »

Approach 2: Based on Package

The in-built function is available from MLmetrics package. Let’s make use of the same.

The syntax for MAPE calculation is

MAPE(y_pred, y_true)

Principal component analysis (PCA) in R »

where:

y_pred: predicted values

y_true: original values

Let’s load the library

library(MLmetrics)

calculate MAPE

MAPE(data$forecast, data$actual)
[1] 0.1926366

Now you can see, exactly the same value we got from our own function from the earlier approach.

Kruskal Wallis test in R-One-way ANOVA Alternative »

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

16 − one =