title: Generating randomly a vector of integers that sum up to N with a given vector of probabilities in R
body: <p>I am trying to find a way to randomly generate vectors that have the following properties:</p>
  
  <p>1) contains only integers.
  2) the integers sum up to a fixed number.
  3) the value of the integer in each position of the vector should be determined by probabilities given by a known vector.</p>
  
  <p>Specifically, I am working with a gridded population dataset, and for each grid I have the share of population of the country living there. I also have a count variable that records how many members of parliament are from each grid (using geocoded birthplace). To evaluate how even or uneven the actual distribution of members of parliament is with respect to population, I need a series of 'mock count variables' that simulate distributions of members of parliaments as if they were roughly proportional to the distribution of the population.</p>
  
  <p>Using the answer to another thread, I have been able to generate a random number of positive integers, given the number of grids and the number of MPs. However, I have no idea of how to assign MPs to a specific element of the vector with probabilities given by a vector of the same length. That is, in this way, each element of the vector is equally likely to get an MP, but what I want is that more populous grids should be more likely to get a higher number of MPs. </p>
  
  <p>Hope this makes sense.</p>
  
  <pre class="lang-r prettyprint-override"><code>
  rand_vect &lt;- function(N, M, sd = 1, pos.only = TRUE) {
    vec &lt;- rnorm(N, M/N, sd)
    if (abs(sum(vec)) &lt; 0.01) vec &lt;- vec + 1
    vec &lt;- round(vec / sum(vec) * M)
    deviation &lt;- M - sum(vec)
    for (. in seq_len(abs(deviation))) {
      vec[i] &lt;- vec[i &lt;- sample(N, 1)] + sign(deviation)
    }
    if (pos.only) while (any(vec &lt; 0)) {
      negs &lt;- vec &lt; 0
      pos  &lt;- vec &gt; 0
      vec[negs][i] &lt;- vec[negs][i &lt;- sample(sum(negs), 1)] + 1
      vec[pos][i]  &lt;- vec[pos ][i &lt;- sample(sum(pos ), 1)] - 1
    }
    vec
  }
  
  rand_vect(gridnumber, MPnumber)
  
  ```r
  
  
  </code></pre>