R 中分段函数的 PMF 和 CDF

问题描述 投票:0回答:2

给定

 p<-function(x){if ( x==-4) {
    0.1
  } else if (x==-1 ) {
   0.2
  } else if ( x==1) {
    0.6
  } else if (x==2 ) {
    0.1
  } else {
   0
  }

我将如何绘制 PMF 和 CDF。没有指定发行版,所以我无法使用内置命令。绘制这些的最佳方法是什么

r probability probability-density piecewise probability-distribution
2个回答
1
投票

更新

如果需要分段CDF,可以尝试定义

cdf
函数

cdf <- function(x) {
    ifelse(
        x <= -4,
        0,
        ifelse(
            x <= -1,
            0.1,
            ifelse(
                x <= 1,
                0.3,
                ifelse(
                    x < 2,
                    0.9,
                    1
                )
            )
        )
    )
}

然后运行

curve(cdf, -5, 5, n = 1e3 + 1)


上一页

尝试 PMF

df <- data.frame(x = c(-4, -1, 1, 2), p = c(.1, .2, .6, .1))
plot(df, type = "l")
points(df)


对于CDF,你可以尝试类似的

plot(df_cdf <- transform(df, p = cumsum(p)), type = "l")
points(df_cdf)


1
投票

简单易行的解决方案:

### support
x = seq(-4,2,1)
### PDF
plot(x,sapply(x,p),ylab="PDF")
### CDF
plot(x,cumsum(sapply(x,p)),ylab="CDF")
© www.soinside.com 2019 - 2024. All rights reserved.