title: Conditional Random Sample in R
body: <p>I am wondering what the best way to solve this is. Essentially I want to generate 20 samples which add to 100 but also where (x1+x2>20). I am struggling to get something that is fast and efficient. I realise that I could filter out the lines that don't meet this criteria but it isn't efficient if I generate 10,000 rather than 20.</p>
  
  <p>The code is as below:</p>
  
  <pre><code>n = 20
  x1 = sample(0:100,n,replace = TRUE)
  x2 = sample(0:100,n,replace = TRUE)
  x3 = sample(0:100,n,replace = TRUE)
  index = (x1+x2+x3)&gt;100
  G=(x1+x2)&gt;20
  while(sum(index)&gt;0&amp;&amp;sum(G)&gt;0){
     x1[index&amp;&amp;G] = sample(0:100,n,replace = TRUE)
     x2[index&amp;&amp;G] = sample(0:100,n,replace = TRUE)
     x3[index&amp;&amp;G] = sample(0:100,n,replace = TRUE)
  index =(x1+x2+x3)&gt;100
  G=(x1+x2)&gt;20
  }
  x4=rep(100,n)-x1-x2-x3
  
  df &lt;- data.frame(x1,x2,x3,x4)
  </code></pre>
  
  <p>Thanks in advance.</p>