Search code examples
rmathstatisticsdistributionderivative

Calculate derivative of Cumulative Distribution (CDF) to get Probability Density (PDF)


The following code calculates the Cumulative Distribution function (CDF) for vector VP. I would like to use the CDF to get the Probability Density function (PDF). In other words, I need to calculate the derivative of CDF. How can I do that in R?

VP <- c(0.36, 0.3, 0.36, 0.47, 0, 0.05, 0.4, 0, 0, 0.15, 0.89, 0.03, 
    0.45, 0.21, 0, 0.18, 0.04, 0.53, 0, 0.68, 0.06, 0.09, 0.58, 0.03, 
    0.23, 0.27, 0, 0.12, 0.12, 0, 0.32, 0.07, 0.04, 0.07, 0.39, 0, 0.25, 
    0.28, 0.42, 0.55, 0.04, 0.07, 0.18, 0.17, 0.06, 0.39, 0.65, 0.15, 
    0.1, 0.32, 0.52, 0.55, 0.71, 0.93, 0, 0.36)
set.seed(0)
CF <- round(sapply(1:1000, function(i) sample(VP, length(VP), replace=TRUE)),2)
Breaks <- c(max(CF,1.0), 1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0)
CDF <- round(sapply(Breaks, function(b) sum(CF<=b)/length(CF)),2)

Solution

  • diff is the discrete difference operator, so I think you're looking for

    diff(CDF)/diff(Breaks)
    
    • note that this vector will be one shorter than the original CDF and Breaks vectors
    • you might have to do something about reversing your CDF and Breaks vectors to get sensible results ...