rfunctionpdfplotcdf

Plotting CDF and PDF in R with custom function


I was wondering if there was any way to plot this PDF and CDF in R. I found these on a different question a user asked, and was curious.

pdfcdf

I know that I have to create a function and then plot this, but I'm struggling with the different parameters and am unsure how to translate this to R. I have only ever plotted PDF/CDF using a normal distribution, or from datasets.


Solution

  • You can write the pdf and cdf as functions, using ifelse to specify the values within the ranges, then simply plot the functions over the desired range:

    pdf <- function(x) {
      ifelse(x >= 0 & x < 1, 0.5, ifelse(x < 1.5 & x >= 1, 1, 0))
    }
    
    cdf <- function(x) {
      ifelse(x < 0, 0,
             ifelse(x >= 0 & x < 1, 0.5 * x,
                    ifelse(x < 1.5 & x >= 1, x - 0.5, 1)))
    }
    
    plot(pdf, xlim = c(-1, 2), type = "s")
    

    
    plot(cdf, xlim = c(-1, 2))
    

    Created on 2022-10-27 with reprex v2.0.2