title: R: function choose, efficient
body: <p>I need to speed up my R-code. My bottleneck is a function that needs to use the choose function. It looks like this:</p>
  
  <pre><code>P_ni &lt;- function(Pn,Pi,eta1,eta2,p,d=NA)
  {
   if(is.na(d)) d &lt;- 1-p
   if(Pn==Pi) output &lt;- p^Pn
   else
   {
    if(Pi==1)seq1 &lt;- seq_len(Pn-1)
    if(Pi&gt;1)seq1 &lt;- seq_len(Pn-1)[-seq_len(Pi-1)]
    output &lt;- sum(choose((Pn-Pi-1),c(seq1-Pi))*choose(Pn,seq1)*
      (eta1/(eta1+eta2))^c(seq1-Pi)*
      (eta2/(eta1+eta2))^c(Pn-seq1)*p^seq1*d^c(Pn-seq1)
    )
   }
   return(output)
  }
  </code></pre>
  
  <p>This function need to be called several times with different Pn and Pi. The Problem here is, that Pn and Pi only are able to take a single number and not work with vectors. This is caused by the choose()-function.</p>
  
  <p>I do this with a for-loop at the moment and it works perfectly, but it is slow.
  The for-loop looks like this:</p>
  
  <pre><code>for(i in 1:nrow(n_k_matrix_p)) 
  {
    n_k_matrix_p[i,4] &lt;- P_ni(n_k_matrix_p[i,1],n_k_matrix_p[i,2],eta1,eta2,p)
  }
  </code></pre>
  
  <p>To make it reproducible:</p>
  
  <pre><code>eta1 &lt;- 10
  eta2 &lt;- 5
  p &lt;- 0.4
  n_k_matrix &lt;- expand.grid(c(1:20),c(1:20))
  n_k_matrix &lt;- n_k_matrix[n_k_matrix[,1] &gt;=n_k_matrix[,2],]
  n_k_matrix &lt;- n_k_matrix[order(n_k_matrix[,1]),]
  </code></pre>
  
  <p>The n_k_matrix contains my numbers for Pn and Pi.
  Unfortunately the loop is still faster than using apply.
  Does anyone have any idea how to speed things up?</p>