Skip to content
Prev 395749 / 398498 Next

DescTools::Quantile

It looks like a homework assignment. It also looks like you didn't read the documentation carefully enough. The 'len.out' argument in seq is solely for specifying the length of a sequence. The 'quantile' function omputes the  empirical quantile of raw data in the vector 'x' at cumulative probabilit(y)(ies) given in the weights' argument, with interpolation I'm between. For example

quantile(x=c(2.3, 1, 7, -4, 1), weights=c(0.60,0.45))
60%  45%
1.52 1.00

So to do what you want, there may be a canned function in R but you can always write your own.

First we write one that takes values in 'x' and weights in 'w', vectors of the same length, and returns the quantile at cumulative probability 'p' for a 'p' of length 1.

"%,%" <-paste0

qtl.one <-
function(p, x, w)
{
    ## argument checking
    bad <- length(x)!=length(w)
    bad <- bad || (length(p)!=1)
    bad <- bad || any(diff(x)<=0)
    if(bad)
      stop("Arguments 'x' and 'w' must be " %,%
      "vectors of the same legnth. Argument " %,%
      "'x' must be a vector of nondecreasing " %,%        "values.")

    if(any(w<=0)||(sum(w)!=1))
      stop("elements of 'w' must be positive " %,%        "and sum to 1")

    ## the actual body of the function
    x[max(which(cumsum(w)<=p))]
}

Now we write a vectorization of the above that will work given a vector of 'p' cumulative probabilities:


qtl <-
function(p, x, w)
{
    if(length(p)==1) ans <- qtl.one(p, x, w)
    if(length(p) >1)
       ans <- sapply(p, FUN=qtl.one, x=x,w=w)
    ans
}
Message-ID: <0jl90u3pcenrwrr0ne8he1vq.1706518675652@email.android.com>
In-Reply-To: <nik2hx53780pep991wulsjns.1706518436647@email.android.com>