title: Using ifelse Within apply
body: <p>I am trying to make a new column in my dataset give a single output for each and every row, depending on the inputs from pre-existing columns.</p>
  
  <p>In this output column, I desire "NA" <strong>if</strong> any of the input vales in a given row are "0". <strong>Otherwise</strong> (if none of the inputs are 0), I want the output for that row to be the number of unique values of the inputs.</p>
  
  <p>I thought that the solution would use an <strong>ifelse</strong> function nested within an <strong>apply</strong> function, but I get an error that I do not understand.</p>
  
  <pre><code>data$output &lt;- apply(data, 1, function(x) {ifelse(x == 0, NA, length(unique(x)))})
  </code></pre>
  
  <blockquote>
    <p>Error in <code>$&lt;-.data.frame</code>(<code>*tmp*</code>, "output", value = c(3L, 3L, 3L, 3L,  : 
      replacement has 3 rows, data has 4</p>
  </blockquote>
  
  <p>I do not know why the replacement has 3 rows, as I thought apply just does the same function to each of my 4 rows.</p>