# Generate values with runif and a probability density function

I'm trying to use the rejection method (accept/reject) to simulate samples of various dimensions from the distribution with density function of probability And graphically check whether the sample comes from a population with Beta distribution (1/2, 3).

Here's what I've done:

 # 1. Define sample size
nvals <- 5000

# 2. Rejection sampling method
reject.beta <- function(nvals)
{
x.aceite <- NULL
u.aceite <- NULL
nx <- 0
x.rejected <- NULL
u.rejected <- NULL
nrejected <- 0
while(nx < nvals) {
Y <- runif(1,0,1) #I can't use uniform distribution
U <- runif(1,0,1.875) #1.875 = 30/16
if(U <= (15/16)*(Y^(-1/2))*(1-Y)^2) {
nx <- nx + 1
x.aceite[nx] <- Y
u.aceite[nx] <- U
} else {
nrejected <- nrejected + 1
x.rejected[nrejected] <- Y
u.rejected[nrejected] <- U
}
}

plot(x.aceite,u.aceite,pch=20,col="green",xlab="x",ylab="f(x)",main="Beta(1/2,3) - pontos escolhidos pelo Método de Rejeição")
lines(x.rejected,u.rejected,pch=20,col="red",type="p")
x.aceite
}

XX <- reject.beta(nvals)
hist(XX,breaks=20,prob=TRUE,xlim=c(0,1),ylim=c(0,3),main="Distribuição(2,3) obtida pelo Método de Rejeição")
x.val <- seq(0,4,0.001)
lines(x.val, dbeta(x.val, 1/2, 3) ,col="blue")


However, I can't use uniform distribution to solve this, I need to use the probability density function: The suggestion I've got was to assign Y variable with a value from this p.d.f using the inversion method. (I thought extracting a value between the min and max would suffice)

Can someone please tell me how can I do that?

I assume you have a cumulative density function $F$ and you want to sample a random variable $Y$ whose distribution functions is $F$ ($Y \sim F$).
To do this note that $F(Y)$ is uniformly distributed. Let $U \sim Uni[0,1]$ then you know that $F^{-1}(U) \sim Y$. This means that all you have to do to sample from $Y$ is to generate a sample $u$ from $U$ and compute $F^{-1}(u)$.
To find $F^{-1}(u)$ in R you might find the function uniroot very useful, since all you really want is a solution for the equation $F(x) = u$.