rprobabilityprobability-densitypiecewiseprobability-distribution

PMF and CDF from a piecewise function in R


Given

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

How would I plot the PMF and CDF. No distribution is specified so I cant use the build in commands. What would be the best way to plot these


Solution

  • Update

    If piece-wise CDF is needed, you can try define cdf function

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

    and then run

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

    enter image description here


    Previous

    Try this for PMF

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

    enter image description here


    For CDF, you can try a similar one

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

    enter image description here