title: R: hierarchical ifelse condition with multiple, parallel outcomes
body: <p>I am looking for an elegant solution to the following problem:</p>
  
  <p>I need to allocate owners to firms based on different matching criteria. These matching criteria are of different quality, hence criteria with weaker quality should only be used if higher quality criteria do not yield results. In my example, all <code>a</code> criteria are of the same quality level and of higher quality than <code>b</code> criteria.</p>
  
  <p>The following to illustrate my point:</p>
  
  <pre><code>firmname &lt;- c("Firm A", "Firm B", "Firm C", "Firm D", "Firm E", "Firm F")
  ownermatch_a1 &lt;- c("Owner 1", NA, NA, NA, "Owner 5", "Owner 6")
  ownermatch_a2 &lt;- c("Owner 1", NA, NA, "Owner 4", "Owner 5", "Owner 6")
  ownermatch_a3 &lt;- c("Owner 1", NA, "Owner 3", "Owner 4", "Owner 5", "Owner 6")
  ownermatch_b1 &lt;- c("Owner 1", "Owner 2", "Owner 3", "Owner 4", "Owner 5", "Owner 6")
  ownerfinal &lt;- (NA)
  
  data.frame(firmname, ownermatch_a1, ownermatch_a2, ownermatch_a3, ownermatch_b1, ownerfinal)
  </code></pre>
  
  <p>This yields the following table</p>
  
  <pre><code> firmname ownermatch_a1 ownermatch_a2 ownermatch_a3 ownermatch_b1 ownerfinal
  1   Firm A       Owner 1       Owner 1       Owner 1       Owner 1       &lt;NA&gt;
  2   Firm B          &lt;NA&gt;          &lt;NA&gt;          &lt;NA&gt;       Owner 2       &lt;NA&gt;
  3   Firm C          &lt;NA&gt;          &lt;NA&gt;       Owner 3       Owner 3       &lt;NA&gt;
  4   Firm D          &lt;NA&gt;       Owner 4       Owner 4       Owner 4       &lt;NA&gt;
  5   Firm E       Owner 5       Owner 5       Owner 5       Owner 5       &lt;NA&gt;
  6   Firm F       Owner 6       Owner 6       Owner 6       Owner 6       &lt;NA&gt;
  </code></pre>
  
  <p>I now want R to do the following:
  1) If any Firm one of the 3 <code>a</code> criteria is non-NA, put it as <code>ownerfinal</code>. 
  2) If there are multiple parallel <code>a</code> non-NA, take any of these randomly and put as <code>ownerfinal</code>
  3) Only if all of these are NA, take <code>ownermatch_b1</code> and put as <code>ownerfinal</code>.</p>
  
  <p>So in the example above:
  Firm A: Pick any of a1, a2, a3
  Firm B: Pick b1
  Firm C: Pick a3
  Firm D: Pick either a2 or a3</p>
  
  <p>Thanks!</p>