# Estimate Probability and Quantile

January 25, 2011
By

(This article was first published on YGC » R, and kindly contributed to R-bloggers)

Simple root finding and one dimensional integrals algorithms were implemented in previous posts.

These algorithms can be used to estimate the cumulative probabilities and quantiles.

Here, take normal distribution as an example.

Normal distribution is defined as:

#probability density function
y.dnorm <- function(x, mean=0, sd=1) exp(-(x-mean)^2/(2*sd^2))/sqrt(2*pi*sd^2)


The cumulative probabilities can be estimated by integrating the PDF function. Here, using function *simpson_v2*, which implemented in previous post, for integral calculation.

y.cdf <- function(pdf=y.dnorm, q) simpson_v2(pdf, -Inf, q)


The quantile function is mathematically the inverse of the cumulative distribution function. Here, the quantile was estimated by using newton-raphson algorithm to find the root of function CDF(q) - p = 0.

?View Code RSPLUS
 1 2 3 4 5 6 7 8 9 10 11  y.qf <- function(pdf=y.dnorm, p, tol=1e-7, niter=100) { x0 = 0 for (i in 1:niter) { fx <- y.cdf(pdf, x0) - p x = x0 - fx/pdf(x0) if (abs(fx) < tol) return(x) x0 = x } stop("exceeded allowed number of iterations") }
> y.dnorm(1)
[1] 0.2419707
> x=y.cdf(pdf=y.dnorm, q=1.64)
> y.qf(pdf=y.dnorm, p=x)
[1] 1.64
> qnorm(p=x)
[1] 1.636615


### Related Posts

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...