 # Median in R

Hi,

I am trying to calculate median() manually but it does not work for impaired lenghted vectors. What is wrong with my code?

``````median_function <- function(x)
{
odered <- sort(x)
if (IsWhole(length(odered)/2) == T) {
odered[length(odered)/2]
} else {
c(odered[(floor(length(odered)/2))],odered[(ceiling(length(odered)/2))])
}
}
median_function(my_matrix[,1])
``````

What does `T` stand for? And, `c()`?

Consider the following pseudo code,

``````ordered <- sort(x)
len <- length(x)
mid <- floor(len / 2)

if (len % 2 == 1) return ordered[mid]

return (ordered[mid - 1] + ordered[mid]) / 2
``````

Eg.

``````x = [25, 79, 45, 12, 37, 69, 91, 54, 83]

ordered = [12, 25, 37, 45, 54, 69, 79, 83, 91]

``````

The floor of 9 / 2 is 4. The median will be at index 4 of the above sorted array. Returned is, `54`.

``````x = [25, 79, 45, 12, 37, 69, 91, 54]

ordered = [12, 25, 37, 45, 54, 69, 79, 91]
 
``````

The floor of 8 / 2 is also 4, the index of the higher order half’s lowest value. Returned will be, `(45 + 54) / 2 => 49.5`

thank you!
This is the lesson
T stands for TRUE and c() is vector. It was in the introduction part of the R course.

As part of the course, it is not requiered but I am trying to write all the built in functions by hand so to understand better the basic coding language.

1 Like

That is the modulo or remainder operator in most languages. It gives us the remainder in a division operation.

``````3 % 2 == 1

13 % 5 == 3
``````

In the case of division by 2, we are checking for odd or even parity.

Will try to catch up to where you are in the course.

Aside

Note that the floor division results in the higher index. The lower index is one less than that, not the ceiling as you have above. That will put both indices in the higher order half of the vector.

This line,

It looks like `IsWhole()` is a predicate function. Do we need to compare it to True? Can it not just be written as,

``````if (IsWhole(length(x) / 2) {
``````

?

1 Like

Many thanks for your help! I modified the code and it works now

1 Like