Rejection sampling
So far, we have showed you how to simulate data from well-defined distributions. However, you may also wish to simulate data from an unknown distribution. The first method we will show you to simulate random variables is through rejection sampling. This method is based on the idea that if you want to sample a random variable from a target distribution, you just have to sample the region under the curve of its density function. For example, let's consider a triangle distribution defined by the following density function:
First, let's plot the function in R by creating a triangle()
function, as follows:
> triangle <- function(x) {(abs(x) < 2) * (2 - abs(x))}
Now, let's create a vector x
to contain the x values and plot the values as follows:
> x<-seq(from=-3,to=3,by=0.001) > plot(x, triangle(x), type = "l", ylim = c(0,2), ylab = as.character("f(x)=(|x < 2|)(2-|x|)"), cex.lab=1.3)
The result is shown in the following plot:
Now if we would like to generate pseudorandom...