Thread: how to compute the absolute value in R?

1. how to compute the absolute value in R?

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.

2. The abs() function is what you're looking for?

___________________________________________

}

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

4. Take a look at what mad does...

PHP Code:
``` > madfunction (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>  ```

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

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

}

anything wrong with my code ??

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)

}

# [1] 0.2298009

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

 Tweet

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts