[R] DescTools::Quantile

Izmirlian, Grant (NIH/NCI) [E] |zm|r||g @end|ng |rom m@||@n|h@gov
Mon Jan 29 10:53:18 CET 2024


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
}

________________________________
From: "Izmirlian, Grant (NIH/NCI) [E]" <izmirlig using mail.nih.gov>
Date: Mon, Jan 29, 2024, 3:55 AM
To: "Izmirlian, Grant (NIH/NCI) [E]" <izmirlig using mail.nih.gov>
Subject: Re: [R] DescTools::Quantile

Greetings,

I am having a problem with DescTools::Quantile
(a function computing quantiles from weighted samples):

# these sum to one
probWeights = c(
     0.0043, 0.0062, 0.0087, 0.0119, 0.0157, 0.0204, 0.0257, 0.0315, 0.0378,
     0.0441, 0.0501, 0.0556, 0.06, 0.0632, 0.0648, 0.0648, 0.0632, 0.06,
     0.0556, 0.0501, 0.0441, 0.0378, 0.0315, 0.0257, 0.0204, 0.0157, 0.0119,
     0.0087, 0.0062, 0.0043
  )
  x = seq(-100,100,length.out=length(probWeights))

  qtls <- DescTools::Quantile(x, weights=probWeights, probs=c(0.1,0.9))

cat("\nQuantiles:\n")
  print(qtls)


Both quantiles are equal to 100!
Is this function working or am I not using it correctly?

Michael Meyer

	[[alternative HTML version deleted]]



More information about the R-help mailing list