Search code examples
rmedian

R median function from scratch


I am a R beginner and I tried to make a median function from scratch.

Here is my code:

mymedian <- function(x) {
  len <- length(x)
  sorted <- sort(x)
  if (len %% 2 == 0) {
    med1 <- sorted[len / 2]
    med2 <- sorted[(len + 1) %/% 2]
    result <- sorted[med1 + med2 / 2]
    return(result)
  } else {
    result <- sorted[(len + 1)/2]
    return(result)
  }
}

Im getting "NA" output. I couldn't find where the problem is.


Solution

  • Main issue is you're trying to index your sorted vector with a non-integer (e.g., 168.5). Compare your function to this:

    mymedian <- function(x){
      len <- length(x)
      sorted <-sort(x)
      if(len%%2==0){
        i <- len/2
        med1<-sorted[i]
        med2 <- sorted[i+1]
        result <- sum(med1,med2)/2
        return(result)
      }else{
        result<-sorted[(len+1)/2]
        return(result)
      }
    }