Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Inverse CDF (kernel) in R?

Tags:

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

like image 747
user2150536 Avatar asked Jan 14 '23 23:01

user2150536


1 Answers

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.

like image 144
Dason Avatar answered Jan 18 '23 19:01

Dason