Rejection Sampling
Im working with rejection sampling with a truncated normal distribution, see r code below. How can I make the sampling stop at a specific n? for example 1000 observations. I.e. I want to stop the sampling when the number of accepted samples has reached n (1000).
Any suggestions? Any help is greatly appreciated :)
#Truncated normal curve
curve(dnorm(x, mean=2, sd=2)/(1-pnorm(1, mean=2, sd=2)),1,9)
#create a data.frame with 100000 random values between 1 and 9
sampled <- data.frame(proposal = runif(100000,1,9))
sampled$targetDensity <- dnorm(sampled$proposal, mean=2, sd=2)/(1-pnorm(1, mean=2, sd=2))
#accept proportional to the targetDensity
maxDens = max(sampled$targetDensity, na.rm = T)
sampled$accepted = ifelse(runif(100000,0,1) < sampled$targetDensity / maxDens, TRUE, FALSE)
hist(sampled$proposal[sampled$accepted], freq = F, col = "grey", breaks = 100, xlim = c(1,9), ylim = c(0,0.35),main="Random draws from skewed normal, truncated at 1")
curve(dnorm(x, mean=2, sd=2)/(1-pnorm(1, mean=2, sd=2)),1,9, add =TRUE, col = "red", xlim = c(1,9), ylim = c(0,0.35))
X <- sampled$proposal[sampled$accepted]
How can I set the length of X to a specific number when I sample?