I am supposed to define a function that can take pdf function as input and return a CDF function (if the input is a vector, then return empirical CDF). It is required that I should enable varying parameters. However, the function integrate in r only deals with one-dimensional functions while pdf usually comes with multiple parameters. So far I can only make pdf a function of x and then use my written function to convert it to CDF.
pdftocdf <- function(pdf, lower){
if(class(pdf)=="function"){
function(quantile) integrate(pdf, lower = lower, upper = quantile)
}
else if(class(pdf)=="numeric") return(ecdf(pdf))
else return("Invalid input")
}
Now I can only define, for example, a chi-squared distribution as following, explicitly specifying the degree of freedom:
pdf <- function(x){
x^(1/2 - 1)*exp(-x/2) / (2^(1/2)*gamma(1/2))
}
In this way, pdftocdf works fine:
cdf <- pdftocdf(pdf, lower=0)
cdf(1) # try with quantile=1
But what I really want to do is:
pdf <- function(x,k){
x^(k/2 - 1)*exp(-x/2) / (2^(k/2)*gamma(k/2))
}
Then put it into function pdftocdf. Any suggestions? Thanks in advance.