Solved – How to generate random data, that’s from Beta distribution with specific density function in R

beta distributiondata visualizationhistogramr

So, considering that $\theta = 2$ and density function is $f(x) = \theta x^{\theta – 1}, 0<x<1$ and $0$ anywhere else, how do I generate random data from this particular distribution?
Here is the code I tried:

x <- rbeta(10000, 1, 2)                              
hist(x)                                                        
curve(dbeta(x, 1, 2), add = TRUE)

First, I don't know if I can generate the data using functon rbeta as my density function is not exactly like ordinary Beta distribution?
Then, when I try to add theoretical distribution's curve, it doesn't appear at all in the region of the histogram, and if I plot it separately it is just a straight line nut a skewed curve like it should be. What am doing wrong?

Best Answer

To obtain the function $f(x) = \theta x^{\theta - 1}$ you need to use rbeta( , 2, 1), not rbeta( , 1, 2) (to see why look into ?rbeta).

density_fun <- function(x,theta=2){
  theta * x^(theta-1)
}

par(mfrow=c(1,2))
x <- rbeta(10000, 2, 1)                              
hist(x, freq=F, col="grey", border="white",main="rbeta(10000, 2, 1)", xlab="x", ylab="f(x)")              
curve(dbeta(x, 2, 1), add = TRUE,lwd=2)

x = seq(0, 1, length.out=500)
plot(x,density_fun(x),col="red", type="l",xlab="x", ylab="f(x)", main=expression(paste(f(x) == theta * x^(theta-1),", with ",theta==2)),lwd=2)

Result: enter image description here Note that you need to plot the histogram using the argument freq=F to plot bars on a probability density scale

As you can see, the function is indeed a straight line; it should not be a curve since for $\theta=2$ you have that $f(x) = 2 x^{2 - 1} = 2x$

Related Question