I am trying to run this code and can't seem to avoid the error 'no loop for break/next, jumping to top level in R. This code worked previously but randomly began showing this error after seemingly no change. Not sure if it is a simple syntax error that I'm missing or something larger.
set.seed(440)
library(ggplot2)
alpha <- 1
xset <- seq(-5, 5 , .001)
zdat <- data.frame(x=xset, y=dlaplace(xset, 1/alpha, 1))
rejection_sampling = function(n, alpha) {
f = dnorm(xset,0,1)
g = dlaplace(xset,0,1)
c <- sqrt(2*exp(1)/pi)
x_sample <- numeric(n)
current_n <- 1
total_samples <- 0
while(current_n <= n) {
y <- dlaplace(1,1,1)
total_samples <- total_samples + 1
a <- rbinom(1, 1, f / (g*c))
if(a == 1) {
x_sample[current_n] = y
current_n <- current_n + 1
}
}
list(
x_sample,
total_samples
)
}
rejection_results = rejection_sampling(10000, 1)
library(ggplot2)
ggplot() +
geom_histogram(data=data.frame(x=rejection_results[[1]]),
mapping=aes(x=x, y=..density..),
bins=30, fill="white", color="black") +
geom_line(data=zdat, color="blue", mapping=aes(x=x, y=y)) + theme_classic()