# how to compute the absolute value in R?

#### xixihaha

##### New Member
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 .

mad <- median(x-median(x)) #dont know what to write here#
}

anybody can help me ? cheers.

Last edited:

#### mp83

##### TS Contributor
The abs() function is what you're looking for?

___________________________________________

#### xixihaha

##### New Member
}

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
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>

#### xixihaha

##### New Member
to be honest, i didnt get the code behind mad. could you just give me any hint? cheers

#### xixihaha

##### New Member
n <- length(x)
for (i in 1:n)

}

anything wrong with my code ??

Last edited:

#### Mike White

##### TS Contributor
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)

}

# [1] 0.2298009