拒绝抽样
我正在使用截断正态分布的拒绝抽样,请参阅下面的 r 代码。如何使采样停止在特定的 n?例如 1000 个观察值。即当接受的样本数量达到n(1000)时,我想停止采样。
有什么建议么?任何帮助是极大的赞赏 :)
#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]
采样时如何将 X 的长度设置为特定数字?