I just found, that when I want a specific type of quantile in R, say the number 3, it doesn't agree with median calculated in the "traditional way" in R.
> set.seed(100); x <- rnorm(100)
> sapply(1:9, function(t) setNames(round(quantile(x, type=t)["50%"], 7), paste("type:", t)))
type: 1 type: 2 type: 3 type: 4 type: 5 type: 6 type: 7 type: 8 type: 9
-0.0688440 -0.0594199 -0.0688440 -0.0688440 -0.0594199 -0.0594199 -0.0594199 -0.0594199 -0.0594199
> median(x)
[1] -0.0594199 # doesn't agree with types 1, 3, 4
I was told, that median() in R is sample median and uses the textbook definition, while quantile() doesn't support the textbook definition in neither way, but rather uses the 1-9 approach described in some book.
Yet the documentation of quantiles also says it's "sample quantile".
So - shouldn't "sample 50% quantile" be equal to "sample median"?
I found that the median() is used also in mean() for case we want the 50% trimmed mean (=median).
So, if I wanted to replicate calculations done by others in other statistical software, like SAS, I have to stick to quantile(), where I can set the type, but I cannot use the median(), which is very often used by others, who don't care of that, so my calculations may diverge somewhere.
Is there any reason behind that in R?
Apart from R, is there any reason for making the sample median different than sample quantile(50%)?
Part of the mean() source code in R:
mean.default <- function(x, trim = 0, na.rm = FALSE, ...)
{
...
if(trim > 0 && n) {
...
if(trim >= 0.5) return(stats::median(x, na.rm=FALSE))
...
}
The median() code:
median.default <- function(x, na.rm = FALSE, ...)
{
...
half <- (n + 1L) %/% 2L
if(n %% 2L == 1L) sort(x, partial = half)[half]
else mean(sort(x, partial = half + 0L:1L)[half + 0L:1L])
}
Source of the quantile(): https://github.com/wch/r-source/blob/trunk/src/library/stats/R/quantile.R
Note to the Moderators: I don't ask "how to do something in R" and the manuals don't answer that general question about any potential reasons for doing that.
median
gives you a simple way,quantile
gives you a bunch of choices. Each of the types returns a valid median. Usually the results are similar, but there would not be any sense in offering choices if they all came to the same results. If you want the same results as SAS you need to figure out, which way SAS computes medians. What exactly is the problem then? $\endgroup$