title: How to Use forcats::fct_collapse in a Function Across Different Dataframes with Different Factor Levels
body: <pre><code>library(tidyverse)
  library(forcats)
  </code></pre>
  <p>I have two simple dataframes (code at bottom) and I want to create a new recoded variable by collapsing the &quot;Animal&quot; column. I usually do this with <code>forcats::fct_collapse</code>. However, I want to make a function to apply fct_collapse to many different dataframes that have the same variables, except that some might be missing one or two of the factor levels. For example, in this case, Df2 is missing &quot;Rhino&quot;.</p>
  <p>Is there a way I can change the code (using pkg:tidyverse) so that factor categories that are missing will be returned as <code>NA</code>? In this example I know it's &quot;Rhino&quot;, but in my real data there may be other missing levels. I'm open to other options besides <code>forcats::fct_collapse</code>, but I would like to stay within the realm of tidyverse.</p>
  <pre><code>REC &lt;- function(Df, Data){
  
  Df %&gt;% 
  mutate(NEW = fct_collapse(Data, One = c(&quot;Cat&quot;,&quot;Dog&quot;,&quot;Snake&quot;),
                            Two = c(&quot;Elephant&quot;,&quot;Bird&quot;,&quot;Rhino&quot;)))
  }
  
  REC(Df1,Animal) - this works
  REC(DF2,Animal) - this doesn't, it throws an error because of &quot;Rhino&quot;
  </code></pre>
  <p>Sample Data:</p>
  <pre><code>Animal &lt;- c(&quot;Cat&quot;,&quot;Dog&quot;,&quot;Snake&quot;,&quot;Elephant&quot;,&quot;Bird&quot;,&quot;Rhino&quot;)
  Code &lt;- c(101,222,434,545,444,665)
  Animal2 &lt;- c(&quot;Cat&quot;,&quot;Dog&quot;,&quot;Snake&quot;,&quot;Elephant&quot;,&quot;Bird&quot;)
  Code2 &lt;- c(101,222,434,545,444)
  
  Df1 &lt;- data_frame(Code, Animal)
  
  Df2 &lt;- data_frame(Code2, Animal2) %&gt; %rename(Animal = Animal2)
  </code></pre>