title: Alternative to which() when no match is found in R
body: <p>The <code>which</code> command removes all rows of data if no element was <code>TRUE</code>. Demonstrating with the <code>iris</code> dataset, let's try to remove rows for a non-existing species.</p>
  
  <pre><code>dim(iris[-which(iris$Species=="nonsense"),])
  # [1] 0 5
  </code></pre>
  
  <p>All rows are deleted, but using the condition directly returns the expected result.</p>
  
  <pre><code>dim(iris[iris$Species!="nonsense",])
  # [1] 150   5
  </code></pre>
  
  <p>This issue was addressed <a href="https://stackoverflow.com/questions/14903728/simple-way-to-delete-dataframe-rows-robust-to-instances-where-no-rows-match-dele">here</a>, and the accepted answer suggested the <code>!=</code> solution above. However, I need to store the condition result in a variable.</p>
  
  <pre><code>x &lt;- which(iris$Species=="nonsense")
  </code></pre>
  
  <p>Should I instead use a logical variable to prevent problems with <code>which</code>? </p>
  
  <pre><code>x &lt;- iris$Species=="nonsense"
  </code></pre>
  
  <p>What is the best and safest practice?</p>