【问题标题】:Plotting the CDF and Quantile Functions Given the PDF绘制给定 PDF 的 CDF 和分位数函数
【发布时间】:2017-03-21 04:58:10
【问题描述】:

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

## 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)
}

【问题讨论】:

  • 可能有用:stats::integrate
  • 您还可以查看library(Ryacas)library(Rsympy)
  • 有点不清楚你在追求什么。我的意思是,您似乎已经知道要从 pdf 转换为 cdf,您需要集成。并非所有功能都可以轻松集成。你的函数有一个解析解。这是您要返回的值吗?或者您只是对任何 pdf 的数值近似感兴趣? R 并不真正了解统计数据;它只是内置了许多统计功能。
  • @MrFlick 我想知道是否有更好的方法来查找 CDF。我也在找分位数函数。
  • @MrFlick @dash2 我应该为b的默认值输入什么?

标签: r inverse cdf


【解决方案1】:

正如@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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多