[R] Generate N random numbers with a given probability and condition

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Thu Jul 12 02:13:47 CEST 2018

On 04/07/2018 6:21 PM, Nelly Reduan wrote:
> Dear all,
> I would like to generate N random numbers with a given probability and condition but I'm not sure how to do this.
> For example, I have N = 20 and the vector from which to choose is seq(0, 10, 1). I have tested:
> x <- sample(seq(0, 10, 1), 20, replace=TRUE, prob=rep(0.28, times=length(seq(0, 10, 1))))
> But I don�t know how to put the condition sum(x) <= max(seq(0, 10, 1)).
> Many thanks for your time

I'd recommend an MCMC solution to this problem.  Set up a distribution 
that is uniform on vectors that satisfy the conditions, with penalties 
on vectors that don't.  Use the Metropolis algorithm with proposals that 
pick a pair of entries and increase one, decrease the other, then let 
MCMC run.  At the end, filter out the cases that violate the conditions.

The hard part is knowing how long to let it run for a satisfactory 
sample, and how correlated later draws will be.  Propp and Wilson's 
perfect sampling algorithm might allow an exact draw, though I don't 
quite see how, and I'm not sure it would be worth the trouble.  Just run 
for a few thousand steps and it should be fine.

Duncan Murdoch

More information about the R-help mailing list