title: Label Encoder functionality in R?
body: <p>In python, scikit has a great function called <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html" rel="noreferrer">LabelEncoder</a> that maps categorical levels (strings) to integer representation. </p>
  
  <p><em>Is there anything in R to do this</em>? For example if there is a variable called color with values {'Blue','Red','Green'} the encoder would translate:</p>
  
  <pre><code>Blue =&gt; 1
  Green =&gt; 2
  Red =&gt; 3
  </code></pre>
  
  <p>and create an object with this mapping to then use for transforming new data in a similar fashion.</p>
  
  <p><strong>Add:</strong>
  It doesn't seem like just factors will work because there is no persisting of the mapping. If the new data has an unseen level from the training data, the entire structure changes. Ideally I would like the new levels labeled missing or 'other' somehow.</p>
  
  <pre><code>sample_dat &lt;- data.frame(a_str=c('Red','Blue','Blue','Red','Green'))
  sample_dat$a_int&lt;-as.integer(as.factor(sample_dat$a_str))
  sample_dat$a_int
  #[1] 3 1 1 3 2
  sample_dat2 &lt;- data.frame(a_str=c('Red','Blue','Blue','Red','Green','Azure'))
  sample_dat2$a_int&lt;-as.integer(as.factor(sample_dat2$a_str))
  sample_dat2$a_int
  # [1] 4 2 2 4 3 1
  </code></pre>