In this tutorial, we will show you how to calculate the RMSE, MAE, and MAPE in R. For all metrics, we will consider the following \(y\) and \(\hat{y}\) and we will verify that we derive the right results by using the Metrics
library.
library(Metrics) y<-c(10, 20, 30, 40, 50, 60) y_pred<-c(9, 22, 28, 34, 55, 58)
RMSE
The formula of the RMSE (Root Mean Square Error) is given by:
\(RMSE = \sqrt{\sum_{i=1}^{n}\frac{(\hat{y_i} – y_i)^2}{n}}\)
Let’s apply the formula and verify the results using the library:
sqrt(sum((y_pred-y)^2)/length(y))
[1] 3.511885
rmse(y, y_pred)
[1] 3.511885
MAE
The formula of the MAE (Mean Absolute Error) is given by:
\(MAE = \sum_{i=1}^{n}\frac{\mid\hat{y_i} – y_i\mid}{n}\)
Let’s apply the formula and verify the results using the library:
sum(abs(y_pred-y))/length(y)
[1] 3
mae(y, y_pred)
[1] 3
MAPE
The formula of the MAPE (Mean Absolute Percentage Error) is given by:
\(MAPE = \frac{1}{n}\sum_{i=1}^{n}\mid\frac{y_i – \hat{y_i}}{y_i}\mid\)
Let’s apply the formula and verify the results using the library:
mean(abs((y_pred-y)/y))
[1] 0.09166667
mape(y, y_pred)
[1] 0.09166667