title: R selecting rows from dataframe using logical indexing: accessing columns by `$` vs `[]`
body: <p>I have a simple R <code>data.frame</code> object <code>df</code>. I am trying to select rows from this dataframe based on logical indexing from a column <code>col</code> in <code>df</code>. </p>
  
  <p>I am coming from the python world where during similar operations i can either choose to select using <code>df[df[col] == 1]</code> or <code>df[df.col == 1]</code> with the same end result.</p>
  
  <p>However, in the R data frame <code>df[df$col == 1]</code> gives an incorrect result compared to <code>df[df[,col] == 1]</code> (confirmed by <code>summary</code> command). I am not able to understand this difference as from links like <a href="http://adv-r.had.co.nz/Subsetting.html" rel="nofollow noreferrer">http://adv-r.had.co.nz/Subsetting.html</a> it seems that either way is ok. Also, <code>str</code> command on <code>df$col</code> and <code>df[, col]</code> shows the same output. </p>
  
  <p>Is there any guidelines about when to use <code>$</code> vs <code>[]</code> operator ?</p>
  
  <p><strong>Edit:</strong>
  digging a little deeper and using this <a href="https://stackoverflow.com/questions/4935479/how-to-combine-multiple-conditions-to-subset-a-data-frame-using-or">question</a> as reference, it seems like the following code works correctly</p>
  
  <p><code>df[which(df$col == 1), ]</code></p>
  
  <p>however, not clear how to guard against <code>NA</code> and when to use <code>which</code></p>