| #' Compute the sample median. |
| #' |
| #' @param x an object for which a method has been defined, or a numeric |
| #' vector containing the values whose median is to be computed. |
| #' @param na.rm a logical value indicating whether 'NA' values should be |
| #' stripped before the computation proceeds. |
| median <- function (x, na.rm = FALSE) { |
| if (is.factor(x) || mode(x) != "numeric") |
| stop("need numeric data") # TODO: Translate message |
| if (na.rm) |
| x <- x[!is.na(x)] |
| else if (any(is.na(x))) |
| return(NA) |
| n <- length(x) |
| if (n == 0) |
| return(NA) |
| half <- (n + 1)/2 |
| if (n%%2 == 1) { |
| sort(x, partial = half)[half] |
| } |
| else { |
| sum(sort(x, partial = c(half, half + 1))[c(half, half + 1)])/2 |
| } |
| } |