Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a function of MAE and RAE without using library(Metrics)?

My goal is to create functions of Mean Absolute Error (MAE) and Relative Absolute Error (RAE) without using any kind of library, like library(Metrics).

I try to input a formula inside a function for both MAE and RAE

mae <- function(a, b)
{
    mean(abs(a, b))
}


rae <- function(a, b)
{
    abs(a,b )
}

However, both function provide different answer compare to the function below,

library(Metrics)
stats <- function(a,b)
    {
        mae <- mae(a,b)
        rae <- rmse(a,b)
    }
like image 345
HYDR0GEN Avatar asked Dec 21 '25 03:12

HYDR0GEN


1 Answers

Your function is wrong. You can use the following function to calculate mae and rae without any package

x <- c(1.1, 1.9, 3.0, 4.4, 5.0, 5.6)
y <- c(0.9, 1.8, 2.5, 4.5, 5.0, 6.2)

mae1 <- function(x,y)
  {
  mean(abs(x-y))
  }

mae1(x, y)
#> [1] 0.25


rae1 <- function(x,y)
  {
  sum(abs(x-y))/sum(abs(x - mean(x)))
  }

rae1(x,y)
#> [1] 0.1666667

library(Metrics)
#> Warning: package 'Metrics' was built under R version 3.6.2

mae(x, y)
#> [1] 0.25
rae(x,y)
#> [1] 0.1666667

Created on 2019-12-27 by the reprex package (v0.3.0)

It is giving same output as that of Metrics package.

Update

If your data contains NAs then the above functions, as well as the functions of package Matrics, will fail. Under such situation use the following code

x <- c(1.1, 1.9, 3.0, 4.4, 5.0, 5.6, NA)
y <- c(0.9, 1.8, 2.5, 4.5, 5.0, 6.2, 2)

mae1 <- function(x,y, na.rm=TRUE)
  {
  mean(abs(x-y), na.rm=na.rm)
  }

mae1(x, y, na.rm=TRUE)
#> [1] 0.25


rae1 <- function(x,y, na.rm=TRUE)
  {
  sum(abs(x-y), na.rm=na.rm)/sum(abs(x - mean(x, na.rm=na.rm)), na.rm=na.rm)
  }

rae1(x,y, na.rm=TRUE)
#> [1] 0.1666667

library(Metrics)
#> Warning: package 'Metrics' was built under R version 3.6.2

mae(x, y)
#> [1] NA
rae(x,y)
#> [1] NA

Created on 2019-12-27 by the reprex package (v0.3.0)

like image 198
Bappa Das Avatar answered Dec 23 '25 21:12

Bappa Das



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!