I've been having difficulty understanding the code for qrule_math
in the survey
package. This document here says this about it:
However, this is not what the code seems to do. Given two vectors of values (x) and weights (w) and a quantile (p) of 0.5 to find the median value:
x <- structure(c(577450.791535772, 919590.385520716, 755016.909933021,
1515808.3277814), .Dim = c(1L, 4L), .Dimnames = list("ing_t_p_R",
c("11110", "31250", "113113", "113118")))
w <- c(`11110` = 311.909858216766, `31250` = 59.2529837088652, `113113` = 34.1247483726328,
`113118` = 69.4310625894021)
p <- 0.5
#First define helper function last():
last <- function (a)
{
if (any(a))
max(which(a))
else 1
}
Function qs
finds an upper and a lower quantile:
qs <- function (x, w, p)
{
n <- length(x)
ii <- order(x)
x <- x[ii]
cumw <- cumsum(w[ii])
pos <- last(cumw <= p * sum(w))
posnext <- if (pos == length(x))
pos
else pos + 1
list(qlow = x[pos], qup = x[posnext], ilow = pos, iup = posnext,
wlow = p - cumw[pos]/sum(w), wup = cumw[posnext]/sum(w) -
p)
}
Then, qrule_math has a condition where it outputs the lower quantile only if wlow
is equal to zero:
qrule_math <- function (x, w, p) {
qdata <- qs(x, w, p)
if (qdata$wlow == 0)
qdata$qlow
else qdata$qup
}
So applying qrule_math
to given x, w and p you get:
qrule_math(x,w,p)
[1] 755016.9
It gets you the upper quantile. This is different from output given by Stata and calculation "by hand" (577451).
So, my question is:
- Is this output correct?
- What does it mean the condition given inside
qrule_math
function, where it gives the lower quantile only ifwlow
is equal to zero? Shouldn't this function give always the quantile that satisfies to be <= p?
c(1,2)
orc(1,2,3,4)
. That will enable you easily to check thatqrule_math
does what it claims (or not--I can only speak to the one example you have supplied). $\endgroup$