2.7 C
London
Thursday, November 28, 2024
HomeStatistics TutorialRHow to Calculate MAPE in R

How to Calculate MAPE in R

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

One of the most common metrics used to measure the forecasting accuracy of a model is MAPE, which stands for mean absolute percentage error.

The formula to calculate MAPE is as follows:

MAPE = (1/n) * Σ(|actual – forecast| / |actual|) * 100

where:

  • Σ – a fancy symbol that means “sum”
  • n – sample size
  • actual – the actual data value
  • forecast – the forecasted data value

MAPE is commonly used because it’s easy to interpret and explain. For example, a MAPE value of 6% means that the average difference between the forecasted value and the actual value is 6%.

This tutorial provides two different methods you can use to calculate MAPE in R.

Method 1: Write Your Own Function

Suppose we have a dataset with one column that contains the actual data values and one column that contains the forecasted data values:

#create dataset
data frame(actual=c(34, 37, 44, 47, 48, 48, 46, 43, 32, 27, 26, 24),
                   forecast=c(37, 40, 46, 44, 46, 50, 45, 44, 34, 30, 22, 23))

#view dataset
data

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

To compute the MAPE, we can use the following function:

#calculate MAPE
mean(abs((data$actual-data$forecast)/data$actual)) * 100

[1] 6.467108

The MAPE for this model turns out to be 6.467%. That is, the average absolute difference between the forecasted value and the actual value is 6.467%.

Method 2: Use a Package

We could also calculate MAPE for the same dataset using the MAPE() function from the MLmetrics package, which uses the following syntax:

MAPE(y_pred, y_true)

where:

  • y_pred: predicted values
  • y_true: actual values

Here is the syntax we would use in our example:

#load MLmetrics package
library(MLmetrics)

#calculate MAPE
MAPE(data$forecast, data$actual)

[1] 0.06467108

This produces the same MAPE value of 6.467% that we calculated using the previous method.

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories