title: How to do target based encoding in R
body: <p>I've a few categorical variables and I'm trying to do a target based encoding on it.
  Following is my code </p>
  
  <pre><code>str(df)
  var1 Factor w/8 levels "1", "2", "3"...
  var2 Factor w/5 levels "1", "3", "5"... etc
  target Factor w/2 levels "1", "0"
  </code></pre>
  
  <p>I'm trying to convert the levels of these factors to the probability of the event rate hence</p>
  
  <pre><code>levels(df$var1) &lt;- table(df$var1, df$target)[,2]/ (table(df$var1, df$target)[,1] + table(df$var1, df$target)[,2])
  </code></pre>
  
  <p>which converts the variables like </p>
  
  <pre><code>str(df)
  var1 Factor w/8 levels "0.0023", "0.08", "0.09"... etc
  </code></pre>
  
  <p>As i wanted to convert these into numerics, I did an as.numeric conversion</p>
  
  <pre><code>df$var1 &lt;- as.numeric(df$var1)
  </code></pre>
  
  <p>But all the values got changed to 1, 2, 3 etc and not the actual probabilities I was looking for i.e. 0.0023, 0.08, 0.09 etc</p>
  
  <p>Is there any way to do so? </p>