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 by xixihaha; 03-09-2010 at 05:34 PM.
[FONT=Fixedsys]
Visit : [/FONT][URL="http://www.statsravingmad.com/"]Site[/URL]|[URL="http://www.statsravingmad.com/blog"]Stats Blog[/URL]|[URL="http://parzakonis.info/"]Personal mini-site[/URL]
[FONT=Fixedsys]Contact : [/FONT][URL="http://www.statsravingmad.com/contact/"]Contact[/URL]
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 by xixihaha; 03-09-2010 at 05:34 PM.
Take a look at what mad does...
PHP Code:
> 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>
[FONT=Fixedsys]
Visit : [/FONT][URL="http://www.statsravingmad.com/"]Site[/URL]|[URL="http://www.statsravingmad.com/blog"]Stats Blog[/URL]|[URL="http://parzakonis.info/"]Personal mini-site[/URL]
[FONT=Fixedsys]Contact : [/FONT][URL="http://www.statsravingmad.com/contact/"]Contact[/URL]
to be honest, i didnt get the code behind mad. could you just give me any hint? cheers
compute.mad <- function(x) {
n <- length(x)
for (i in 1:n)
mad <- median(abs(x[i]-median(x)))
}
anything wrong with my code ??
Last edited by xixihaha; 03-10-2010 at 03:37 PM.
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
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
Tweet |