# How can I one-hot encode a variable that has only 2 levels? [closed]

I'm trying to do OHC in R to convert categorical into numerical data. However R's caret package requires one to use factors with greater than 2 levels. Any idea how to go around this? I've searched and not found a solution. I would do label encoding for instance but that would defeat the whole purpose of OHC. Thanks in advance.

## closed as off-topic by kjetil b halvorsen, Peter Flom♦Nov 26 '18 at 10:37

This question appears to be off-topic. The users who voted to close gave this specific reason:

• "This question appears to be off-topic because EITHER it is not about statistics, machine learning, data analysis, data mining, or data visualization, OR it focuses on programming, debugging, or performing routine operations within a statistical computing platform. If the latter, you could try the support links we maintain." – kjetil b halvorsen, Peter Flom
If this question can be reworded to fit the rules in the help center, please edit the question.

• does the caret::dummyVars function not do what you need ? – Robert Long Nov 24 '18 at 16:28
• It doesn't. I have factors with only 2 and some with onlly 1 level. The dummyVars function requires greater than 2 factors. I did not want to discard these columns. – NelsonGon Nov 24 '18 at 17:05
• Just recode as 0/1 numeric yourself – kjetil b halvorsen Nov 24 '18 at 18:02

One-hot encoding is commonly used in pre-processing data as inputs to machine learning algorithms. For factors with more than 2 levels, this involves creating one or more dummy variables. If a factor has only 2 levels then no dummy variables are needed - indeed it may be already one-hot encoded. Just check the levels (for example in R, use levels(varname)). If they are not 0 and 1, then just change them to 0 and 1 and you should be good to go. An example in R:

> x <- factor(c("alpha","beta","alpha","beta","alpha","beta"))
> length(x)
[1] 6

> x
[1] alpha beta  alpha beta  alpha beta
Levels: alpha beta

> levels(x) <- c(0,1)
> x
[1] 0 1 0 1 0 1
Levels: 0 1


You also mentioned factors with only 1 level. Such factors are not variables and could be removed from the dataset (as they are constants and will not affect predictions), but if it were me I would investigate why a single-factor variable is there in the first place.

• That solved it, how would I automate it if many factors have only two levels though? – NelsonGon Nov 24 '18 at 17:29
• Something like this: newData <- lapply(oldData[, the.vars], function(x) {levels(x) <- c(0,1)}) where the.vars are the column numbers – Robert Long Nov 24 '18 at 18:07