title: create binary encoded columns based on levels of data frame's factors meta data
body: <p>I would like to create &quot;binary encoding columns&quot; of factor columns. There are various codes out there, which work fine for data frames with many rows (i.e. which have at least one row for each level). My use case is that I may only have the factors levels as &quot;meta data&quot; in the data frame.</p>
  <p>So given a data frame like this:</p>
  <pre><code>haves &lt;- data.frame(x = &quot;a&quot;)
  haves$x &lt;- factor(as.character(haves$x), ordered = FALSE, levels = c(
          &quot;a&quot;
          , &quot;b&quot;
          , &quot;c&quot;
      ))
  </code></pre>
  <p>I would like to obtain this (based on 3 levels =&gt; ceiling(log2(3)) =&gt; 2 columns):</p>
  <pre><code>x bin_x_1 bin_x_2
  a       0       0 
  </code></pre>
  <p>I made an attempt below, which does not fully work.</p>
  <pre><code>library(binaryLogic)
  
  encode_binary &lt;- function(x, name = &quot;binary_&quot;) {
      x2 &lt;- as.binary(unique(unclass(x)) - 1)
      maxlen &lt;- ceiling(log2(nlevels(x)))
      x2 &lt;- lapply(x2, function(y) {
          l &lt;- length(y)
          if (l &lt; maxlen) {
              y &lt;- c(rep(0, (maxlen - l)), y)
          }
          y
      })
      d &lt;- as.data.frame(t(as.data.frame(x2)))
      rownames(d) &lt;- NULL
      colnames(d) &lt;- paste0(name, 1:maxlen)
      d
  }
  
  haves &lt;- data.frame(x = &quot;a&quot;)
  haves$x &lt;- factor(as.character(haves$x), ordered = FALSE, levels = c(
          &quot;a&quot;
          , &quot;b&quot;
          , &quot;c&quot;
      ))
  
  wants &lt;- cbind(haves, encode_binary(haves[[&quot;x&quot;]], name = &quot;bin_x_&quot;))
  wants
  </code></pre>
  <p>PS:</p>
  <p>ceiling(log2(n)) determines how many columns/bits are required to encode levels.</p>