title: Create a new column based on a dictionary using R
body: <p>For the following dataframe <code>d</code>, I'm trying to create a new column by replacing <code>col1</code> using a dictionary <code>dict_to_replace</code>:</p>
  <pre><code>library(tidyverse)
  library(stringr)
  
  d &lt;- data.frame(col1 = c(&quot;AA&quot;, &quot;AG&quot;, &quot;AC&quot;, &quot;AA&quot;), col2 = c(NA, &quot;GG&quot;, &quot;GG&quot;, &quot;GC&quot;), stringsAsFactors=FALSE)
  dict_to_replace &lt;- c('AA'='a', 'AG'='b')
  
  d %&gt;% 
    mutate(
      col3 = str_replace_all(col1, pattern = dict_to_replace)
    )
  </code></pre>
  <p>Out:</p>
  <pre><code>  col1 col2 col3
  1   AA &lt;NA&gt;    a
  2   AG   GG    b
  3   AC   GG   AC
  4   AA   GC    a
  </code></pre>
  <p>But I expected if the values in <code>col1</code> is not in the key of <code>dict_to_replace</code>, then replace by <code>NA</code> instead of values in <code>col1</code>, which means the expected result will like this:</p>
  <pre><code>  col1 col2 col3
  1   AA &lt;NA&gt;    a
  2   AG   GG    b
  3   AC   GG  &lt;NA&gt;
  4   AA   GC    a
  </code></pre>
  <p>How could I achieve that in pipe (%&gt;%) using R? Thanks.</p>