根据PDF绘制CDF和分位数函数

时间:2017-03-21 04:58:11

标签: r inverse cdf

如果我有PDF,我将如何绘制R中的CDF和分位数函数。目前,我有以下内容(但我认为必须有更好的方法):

## Probability Density Function
p <- function(x) {
  result <- (x^2)/9
  result[x < 0 | x > 3] <- 0
  result
}

plot(p, xlim = c(0,3), main="Probability Density Function")

## Cumulative Distribution Function
F <- function(a = 0,b){
  result <- ((b^3)/27) - ((a^3)/27)
  result[a < 0 ] <- 0
  result[b > 3] <- 1
  result
}

plot(F(,x), xlim=c(0,3), main="Cumulative Distribution Function")

## Quantile Function
Finv <- function(p) {
  3*x^(1/3)
}

1 个答案:

答案 0 :(得分:2)

正如@ dash2建议的那样,CDF需要你整合PDF,实质上需要你找到曲线下的区域。

这是一个应该有用的通用解决方案。我使用高斯分布作为一个例子 - 你应该能够向它提供任何通用函数。

请注意,报告的分位数仅为近似值。另外,不要忘记查看integrate()的文档。

# CDF Function
CDF <- function(FUNC = p, plot = T, area = 0.5, LOWER = -10, UPPER = 10, SIZE = 1000){

    # Create data
    x <- seq(LOWER, UPPER, length.out = SIZE)
    y <- p(x)

    area.vec <- c()
    area.vec[1] <- 0

    for(i in 2:length(x)){
        x.vec <- x[1:i]
        y.vec <- y[1:i]

        area.vec[i] = integrate(p, lower = x[1], upper = x[i])$value
    }

    # Quantile
    quantile = x[which.min(abs(area.vec - area))]

    # Plot if requested
    if(plot == TRUE){

        # PDF
        par(mfrow = c(1, 2))
        plot(x, y, type = "l", main = "PDF", col = "indianred", lwd = 2)
        grid()

        # CDF
        plot(x, area.vec, type = "l", main = "CDF", col = "slateblue",
             xlab = "X", ylab = "CDF", lwd = 2)

        # Quantile 
        mtext(text = paste("Quantile at ", area, "=",
                           round(quantile, 3)), side = 3)
        grid()

        par(mfrow = c(1, 1))
    }
}

# Sample data
# PDF Function - Gaussian distribution
p <- function(x, SD = 1, MU = 0){
    y <- (1/(SD * sqrt(2*pi)) * exp(-0.5 * ((x - MU)/SD) ^ 2))
    return(y)
}

# Call to function
CDF(p, area = 0.5, LOWER = -5, UPPER = 5)

enter image description here