knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library(cdsamplr)
This package provides functions that allow for sampling from continuous random variable distributions.
The idea behind rejection sampling is to: a. test the location of values that are uniformly and randomly sampled b. keep values that fall under the region of the probability density funciton c. reject values that fall outside of the region of the probability density function
How it is done: 1. start with a proposed sample from a uniform distribution between a and b 2. select a critical value by using a uniform distribution between 0 and C (where C is the maximum of the density function) 3. compute the pdf of the proposed sample 4. compare the critical value to the pdf of the proposed 5. if the critical value is less than the pdf of the proposed, store the proposed sample in a variable
Here is an example of Rejection_Samplr using the uniform distribution.
sim_data <- rejection_samplr(1300, dunif, 0,1,2) hist(sim_data, probability = TRUE) curve(dunif(x), col = "red", add = TRUE)
Here is an example of Rejection_Samplr using a custom probability density function.
my_pdf <- function(x) { ifelse(x>=0 & x<=2, (x/2), 0)} sim_data <- rejection_samplr(30000, my_pdf, 0,2,1) hist(sim_data, probability = TRUE) curve(my_pdf(x), col = "red", add = TRUE)
Here is an example of Rejection_Samplr using a beta probability density function. It has a set pdf where shape1= 2 and shape2= 3.
pdf_beta <- function(x) { dbeta(x, shape1 = 2, shape2 = 3) } sim_data <- rejection_samplr(1300, pdf_beta, a = 0,b = 1,C =1.5) hist(sim_data, probability = TRUE) curve(dbeta(x,2,3), col = "red", add = TRUE)
The idea behind this sampling techinique is to generate samples from a continuous 2D distribution defined on a square. The samples come in the form of pairs (x and y)
How it is done: 1. start by taking two proposed samples - each from a uniform distribution between a and b 2. select a critical value by using a uniform distribution between 0 and C (where C is the maximum of the joint density function) 3. compute the joint pdf of the two proposed samples 4. compare the critical value to the joint pdf of the proposed samples 5. if the critical value is less than the joint pdf of the proposed, store the proposed samples in a data frame
Here is an example of samplr2D using the joint pdf of two independent uniform random variables each with min = 0 and max = 1
unif_jpdf <- function(x,y, min = 0, max = 1){ x <- dunif(x, min = min, max = max) y <- dunif(y, min = min, max = max) x*y } test <- samplr2D(n = 2000, jpdf = unif_jpdf, a = 0, b = 1, C = 1)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.