title: Pre-multiply by excluding NA in R
body: <p>Here is sample data:</p>
  
  <pre><code>set.seed(123)
  covar1 &lt;- matrix(sample(c(NA, 1:3), 10, replace = TRUE), 10,1)
  covar2 &lt;- matrix(sample(c(NA, 1:3), 10, replace = TRUE), 10,1)
  covar3 &lt;- matrix(sample(c(NA, 1:3), 10, replace = TRUE), 10,1)
  covar4 &lt;- matrix(sample(c(NA, 1:3), 10, replace = TRUE), 10,1)
  covar5 &lt;- matrix(sample(c(NA, 1:3), 10, replace = TRUE), 10,1)
  
  df &lt;- as.data.frame(cbind(covar1,covar2,covar3,covar4,covar5))
  names(df) &lt;- c("covar1","covar2","covar3","covar4","covar5")
  </code></pre>
  
  <p>And these are my 3 models with parameters each coresponding to covariate as in <code>df</code></p>
  
  <pre><code>model0 &lt;- data.frame(covar1=4,covar5=7)
  model1 &lt;- data.frame(covar1=2,covar3=5,covar4=3)
  model2 &lt;- data.frame(covar1=2,covar2=5,covar3=3,covar5=7)
  </code></pre>
  
  <p>Now, I would like to choose model0-2 and premultiply with corresponding row from <code>df</code>. The rows of df which do not meet the matching criteria would give <code>NA</code>. </p>
  
  <p>The intentition is to always use the longest model out of the 3 avaiable. So if the row matches the 4 covariate model = model2, that <code>df</code> row should be premultiplied with the model2 if there isn't match should try model1 or model0 the shortes. </p>
  
  <p>Desired output: </p>
  
  <pre><code>      covar1 covar2 covar3 covar4 covar5 Output Model
   1      NA      2      3     NA     NA     NA
   2       1     NA      2      2      2     18    m1    # (1*2)+(2*5)+(2*3)=18
   3       3      1      2      1      1     21    m2    # (1*3)+(1*5)+(3*2)+(7*1)=21
   4      NA      1     NA      3      2     NA          # (1*2)+(2*5)+(2*3)=18
   ..
   .. 
  </code></pre>
  
  <p>Now, I'm not going to write what I have tried as this would include even more information, which usually SO users don't like. For something like this there may be even package out there. Any hint or help is very much appreciated.  </p>