Search code examples
rcdf

R. I have a vector with values. I would like to implement a formula that uses CDF and PDF


Suppose that I have a vector with values, for example:

MyVector=(99,100,100,98,99,101,99,101,102,100)

From here I would like to use a formula that would give me CDF(x)/PDF(x) for those values of x that are defined. I can use the function ecdf to get the numerator:

MyCDF <- ecdf(MyVector)

Then I would be able to write, say, MyCDF(100) which would give me 0.7 as the result.

But it looks like there is no similar function for PDF (the denominator)?

As a result I would like to be able to get the following table in the example above:

Value PDF CDF CDFdivPDF
98 0.1 0.1 1
99 0.3 0.4 1.33
100 0.3 0.7 2.33
101 0.2 0.9 4.5
102 0.1 1 10

Also, I would like to make a plot where values are on the x-axis, and PDF, CDF, CDFdivPDF are plotted.

Could you please help? Thank you in advance!


Solution

  • You should use ecdf like below

    x <- sort(unique(MyVector))
    cdf <- ecdf(MyVector)(x)
    pdf <- diff(c(0, cdf))
    
    data.frame(
        value = x,
        CDF = cdf,
        PDF = pdf,
        CDFdivPDF = cdf / pdf
    )
    

    such that

      value CDF PDF CDFdivPDF
    1    98 0.1 0.1  1.000000
    2    99 0.4 0.3  1.333333
    3   100 0.7 0.3  2.333333
    4   101 0.9 0.2  4.500000
    5   102 1.0 0.1 10.000000