Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Recently I had to define a R function that would compute the
Problem statement
Suppose we are interested in numerically computing the
and
Optimization
This problem can be cast into an optimization problem,
That said, all we need is a numerical optimization routine to find
Below is one possible implementation of this strategy in R, using the integrate
function for numerical integration and nlminb
for the numerical optimization.
CDF <- function(x, dist){ integrate(f=dist, lower=-Inf, upper=x)$value } objective <- function(x, quantile, dist){ (CDF(x, dist) - quantile)^2 } find_quantile <- function(dist, quantile){ result = nlminb(start=0, objective=objective, quantile = quantile, dist = dist)$par return(result) }
and we can test if everything is working as it should using the following
simple task of computing the 95th-quantile of the standard Gaussian distribution.
std_gaussian <- function(x){ dnorm(x, mean = 0, sd = 1) } find_quantile(dist = std_gaussian, quantile = 0.95) [1] 1.644854 qnorm(0.95) [1] 1.644854
Random variables with bounded domain
If
For example, if
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.