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
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)  6 > x  alpha beta alpha beta alpha beta Levels: alpha beta > levels(x) <- c(0,1) > x  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.