title: R finding values in a data frame using | operator vs %in%
body: <p>I'm trying to find all instances of certain values in a data frame, and replace them with NA. I tried this two different ways that I thought were equivalent, but I get different results. For example:</p>
  
  <pre><code>df &lt;- data.frame(a=c(1,2),b=c(3,4))
  df[df == 1 | df == 4] &lt;- NA
  </code></pre>
  
  <p>gives me the expected result:</p>
  
  <pre><code>df
  #    a  b
  # 1 NA  3
  # 2  2 NA
  </code></pre>
  
  <p>whereas</p>
  
  <pre><code>df &lt;- data.frame(a=c(1,2),b=c(3,4))
  df[df %in% c(1,4)] &lt;- NA
  </code></pre>
  
  <p>does nothing:</p>
  
  <pre><code>df
  #    a b
  # 1  1 3
  # 2  2 4
  </code></pre>
  
  <p>This seems to be because if I use the "|" operator, it searches the data frame element by element, whereas if I use %in% it searches the data frame vector by vector (column by column), but I don't understand why.</p>
  
  <pre><code>df &lt;- data.frame(a=c(1,2),b=c(3,4))
  df == 1 | df == 4
  #         a     b
  # [1,]  TRUE FALSE
  # [2,] FALSE  TRUE
  
  df %in% c(1,4)
  # [1] FALSE FALSE
  </code></pre>