how to compute the absolute value in R?

#1
the median absolute deviance (mad) of a vector x=(x1,x2....xn) is defined as the median of the absolute differences between each observation and the median of vector x, i.e
mad(x )= median{ | x1-median(x) | ,..., | xn-median(x) | }

im going to write a function called compute.mad to calculate the mad, but i know how to code the absolute value.

i also have another question which is how to reprent each entry of matrix x such as x1,x2....



im not allowed to use the build-in function mad .


compute.mad <- function(x) {
mad <- median(x-median(x)) #dont know what to write here#
mad
}

anybody can help me ? cheers.
 
Last edited:
#3
compute.mad <- function(x) {
mad <- median(abs(x-median(x)))
mad
}


i dont think my code is right, because my answer is not consistent with what the build-in function mad got. could anybody help me with my second question? thanks
 
Last edited:

mp83

TS Contributor
#4
Take a look at what mad does...

PHP:
> mad
function (x, center = median(x), constant = 1.4826, na.rm = FALSE, 
    low = FALSE, high = FALSE) 
{
    if (na.rm) 
        x <- x[!is.na(x)]
    n <- length(x)
    constant * if ((low || high) && n%%2 == 0) {
        if (low && high) 
            stop("'low' and 'high' cannot be both TRUE")
        n2 <- n%/%2 + as.integer(high)
        sort(abs(x - center), partial = n2)[n2]
    }
    else median(abs(x - center))
}
<environment: namespace:stats>
 
#6
compute.mad <- function(x) {
n <- length(x)
for (i in 1:n)
mad <- median(abs(x-median(x)))

}

anything wrong with my code ??
 
Last edited:

Mike White

TS Contributor
#7
You do not need to use the for loop. Your original code was ok.

The reason that your code gives a different result to the mad function is due to the additional parameters that the mad function uses. The mad fuction has a factor to adjust for asymptotically normal consistency (not sure what this means, but someone may be able to explain). If you set the constant to 1 the mad function gives the same result as your function.

Code:
set.seed(1)
x<-runif(100)

compute.mad <- function(x) {
mad <- median(abs(x-median(x)))
mad
}

mad(x, constant=1)
# [1] 0.2298009

compute.mad(x)
# [1] 0.2298009
 
#8
i understant now, coz the build-in function uses the constant 1.4826, my answer times that constant will give the same answer as mad. thank you Mike. much appreciated