user2150536
user2150536

Reputation: 61

How to get Inverse CDF (kernel) in R?

Is there any function in R which will calculate the inverse kernel(i am considering normal) CDF for a particular alpha(0,1). I have found quantile but I am not sure how it works.

Thanks

Upvotes: 6

Views: 13597

Answers (2)

Greg Snow
Greg Snow

Reputation: 49640

An alternative approach would be to use log-spline density estimation rather than kernel density estimation. Look at the 'logspline' package. With logspline density estimations you get CDF (plogspline) and inverse CDF (qlogspline) functions.

Upvotes: 2

Dason
Dason

Reputation: 61913

We can integrate to get the cdf and we can use a root finding algorithm to invert the cdf. First we'll want to interpolate the output from density.

set.seed(10000)
x <- rnorm(1000, 10, 13)
pdf <- density(x)

# Interpolate the density
f <- approxfun(pdf$x, pdf$y, yleft=0, yright=0)
# Get the cdf by numeric integration
cdf <- function(x){
  integrate(f, -Inf, x)$value
}
# Use a root finding function to invert the cdf
invcdf <- function(q){
  uniroot(function(x){cdf(x) - q}, range(x))$root
}

which gives

med <- invcdf(.5)
cdf(med)
#[1] 0.5000007

This could definitely be improved upon. One issue is that I don't guarantee that the cdf is always less than or equal to 1 (and if you check the cdf for values larger than max(x) you might get something like 1.00097. But I'm too tired to fix that now. This should give a decent start.

Upvotes: 9

Related Questions