transform columns to binary encoded columns in R I have some nominal variables encoded as integers (not ordinal), which I would like to encode as binary (not dummies nor one hot!). The following code is what I came up with (adapted from other code I found). Is this a valid/scalable approach? Thanks!
library(binaryLogic)

df &lt;- data.frame(x1 = c(1, 1, 2, 3), x2 = c(1, 2, 3, 4))

encode_binary &lt;- function(x, name = &quot;binary_&quot;) {
    x2 &lt;- as.binary(x)
    maxlen &lt;- max(sapply(x2, length))
    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
}

df &lt;- cbind(df, encode_binary(df[[&quot;x1&quot;]], name = &quot;binary_x1_&quot;))
df &lt;- cbind(df, encode_binary(df[[&quot;x2&quot;]], name = &quot;binary_x2_&quot;))

df
If we test on larger vector your approach is quite slow:
test_vec &lt;- 1:1e5
system.time(v1 &lt;- encode_binary(test_vec, name = &quot;binary_x1_&quot;))
#  user  system elapsed 
# 22.23    0.08   22.37 

Based on this SO question
I managed to write code that performs a lot faster:
encode_binary2 &lt;- function(x, name = &quot;binary_&quot;) {
  m &lt;- sapply(x, function(x) rev(as.integer(intToBits(x))))
  tm &lt;- t(m)
  # remove empty bit cols
  i &lt;- which(colSums(tm) != 0L)[1]
  tm &lt;- tm[, i:ncol(tm)]
  # save to data.frame
  d &lt;- as.data.frame(tm)
  rownames(d) &lt;- NULL
  colnames(d) &lt;- paste0(name, 1:ncol(d))
  d
}

system.time(v2 &lt;- encode_binary2(test_vec, name = &quot;binary_x1_&quot;))
# user  system elapsed 
# 0.61    0.02    0.63 

# test that results are equal:
all.equal(v1, v2)
# [1] TRUE