title: One-Hot Encoding in [R] | Categorical to Dummy Variables
body: <p>I need to create a new data frame <strong>nDF</strong> that binarizes all categorical variables and at the same time retains all other variables in a data frame <strong>DF</strong>. For example, I have the following feature variables: RACE (4 types) and AGE, and an output variable called CLASS. </p>
  
  <p>DF =</p>
  
  <pre>
                RACE     AGE (BELOW 21)      CLASS
  Case 1    HISPANIC                  0          A
  Case 2       ASIAN                  1          A
  Case 3    HISPANIC                  1          D
  Case 4   CAUCASIAN                  1          B
  </pre>
  
  <p>I want to convert this into nDF with five (5) variables or four (4) even:</p>
  
  <pre>
            RACE.1    RACE.2    RACE.3      AGE (BELOW 21)     CLASS
  Case 1         0         0         0                   0         A
  Case 2         0         0         1                   1         A
  Case 3         0         0         0                   1         D
  Case 4         0         1         0                   1         B
  </pre>
  
  <p>I am familiar with the treatment contrast to the variable <strong>DF</strong>$RACE. However, if I implement </p>
  
  <pre><code>contrasts(DF$RACE) = contr.treatment(4)
  </code></pre>
  
  <p>what I get is still a <strong>DF</strong> of three variables, but with variable <strong>DF</strong>$RACE having the attribute "contrasts."</p>
  
  <p>What I ultimately want though is a new data frame <strong>nDF</strong> as illustrated above, but which can be very tedious to evaluate if one has around 50 feature variables, with more than five (5) of them being categorical variables. </p>