samplr: Single and Two Variable Rejection Sampler

Description Usage Arguments Value Examples

View source: R/samplr.R

Description

This function implements both one and two variable rejection sampling for probability density functions which are bounded, but the support does not need to be bounded.

Usage

1
samplr(N, f, twod = FALSE)

Arguments

N

The number of samples returned by the rejection sampler.

f

The pdf that we are sampling from, input as a predefined function. For one variable, the input variable must be declared as x. For two variables, the parameter of the function must be a vector containing the variables x and y.

twod

Specification if the input pdf is two dimensional if TRUE. Default is FALSE, meaning that the input function is one dimensional.

Value

If using a single variable, the output is a vector containing the samples. If two variables, the output is a matrix with N rows and 2 columns containing the samples.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
Single variable

f <- function(x) {
  ifelse(0 < x & x < 1, 2*x, 0)
}
hist(samplr(10000,f))

g <- function(x) {
  ifelse(0 < x & x < 2, 1/2*x, 0)
}
hist(samplr(10000,g))

h <- function(x) {
  ifelse(0 < x & x < 6.2832, 1/2/pi*(sin(x) + 1), 0)
}
hist(samplr(10000,h))

u <- function(x) {
  ifelse(x < 0, 1/2*exp(x), 1/2*exp(-x))
}
hist(samplr(10000,u))

Two dimensional (requires ggplot2)

v <- function(z) {
  x <- z[1]
  y <- z[2]
  ifelse(0 <= x & x <= 1 & 0 <= y & y <= 1, x + y, 0)
}
samps <- data.frame(samplr(10000, v, twod = TRUE))
colnames(samps) <- c("x","y")
ggplot(samps, aes(x, y)) +
  geom_density_2d()

w <- function(z) {
  x <- z[1]
  y <- z[2]
  ifelse(0 <= x & x <= 1 & 0 <= y & y <= 1 & 0 <= x + y & x + y <= 1, 24*x*y,0)
}
samps <- data.frame(samplr(10000, w, twod = TRUE))
colnames(samps) <- c("x","y")
ggplot(samps, aes(x, y)) +
  geom_density_2d()

l <- function(z) {
  x <- z[1]
  y <- z[2]
  ifelse(0 < x & 0 < y, exp(-x)*exp(-y), 0)
}
samps <- data.frame(samplr(10000, l, twod = TRUE))
colnames(samps) <- c("x","y")
ggplot(samps, aes(x, y)) +
  geom_density_2d()

bubj/samplr documentation built on May 28, 2019, 7:14 p.m.