Search code examples
rmedian

Writing a median function in R


I have been tasked to write my own median function in R, without using the built-in median function. If the numbers are odd; calculate the two middle values, as is usual concerning the median value. Something i probably could do in Java, but I struggle with some of the syntax in

R Code:

list1 <- c(7, 24, 9, 42, 12, 88, 91, 131, 47, 71)

sorted=list1[order(list1)]
sorted
n = length(sorted)
n
if(n%2==0) # problem here, implementing mod() and the rest of logic.

Solution

  • Here is a self-written function mymedian:

    mymedian <- function(lst) {
      n <- length(lst)
      s <- sort(lst)
      ifelse(n%%2==1,s[(n+1)/2],mean(s[n/2+0:1]))
    }
    

    Example

    list1 <- c(7, 24, 9, 42, 12, 88, 91, 131, 47, 71)
    list2 <- c(7, 24, 9, 42, 12, 88, 91, 131, 47)
    mymedian(list1)
    mymedian(list2)
    

    such that

    > mymedian(list1)
    [1] 44.5
    
    > mymedian(list2)
    [1] 42