1

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.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
ireliatt
  • 11
  • 1
  • 1
    When you have a two parameter pdf, what exactly do you want the behavior to be? In your example, how would you specify the value of `k`? You can't really have a free variable unless you want to do some type of symbolic integration which isn't a part of base R. I'm unsure what your desired function would look like given your description. – MrFlick Oct 19 '20 at 04:04

0 Answers0