R - create new column dataframe based on index of value match with existing column
<p>I have a dataframe called <code>imp2</code> (with about 6,000 rows) for which there are 9 columns labeled <code>'savres1'...'savres9'</code>. Values in each of these columns are either 1 or 0. For each row, the value of only 1 of these columns is 1 (rest are 0).</p>

<p>I'd like to create a new column called <code>'savres'</code> into which I would put a value between 1 and 9 that matches the index of the column (within this set of 9 columns) which holds the 1 value. E.g. if <code>'savres7'</code> is 1 and the rest of these columns are 0, then <code>savres</code> should equal 7.</p>

<p>I've used several variations of <code>which</code>, <code>match</code> and <code>%in%</code> to find the value, but I'm not getting the output I expect.</p>

<p>Below is a recent trial function and a sample set of rows that are created in the dataframe. </p>

<p>Recent attempted solution:</p>

<pre><code>imp2 &lt;- within(imp2, savres &lt;- which(c(savres1, savres2, savres3, savres4, savres5, savres6, savres7, savres8, savres9) == 1) %% 9 + 1)
</code></pre>

<p>Results:</p>

<p>(Note, I didn't include all columns, but from the 4 here, you can see that the function isn't working - the <code>'savres'</code> value in row 4 should be 3 and those for rows 1 and 2  should not be 4 or 2)</p>

<pre><code>sample &lt;- head(imp2[c('savres1','savres2','savres3','savres4')],4)

savres | savres1 | savres2 | savres3 | savres4
4      |     0   |    0    |    0    |    0
2      |   0     |    0    |    0    |    0
1      |   1     |    0    |    0    |   0
1      |   0     |   0     |  1      |   0
</code></pre>

<p>Can anyone recommend a solution?</p>

<p>I thought this should be a fairly simple operation, but I've been frustrated with a number of approaches I've tried.</p>