| one.hot | R Documentation |
One-hot encode categorical columns using base R. Character columns are converted to factors, with levels in order of first appearance.
one.hot(data, cols = "auto", sparsifyNAs = FALSE, naCols = FALSE,
dropCols = FALSE, dropUnusedLevels = FALSE)
data |
A vector, matrix, |
cols |
Column names or positive integer column indices to encode.
The default, |
sparsifyNAs |
Logical. If |
naCols |
Logical. If |
dropCols |
Logical. If |
dropUnusedLevels |
Logical. If |
Level indicators are integer columns named column_level. They follow
their original column in factor-level order. When requested, the missing-value
indicator is named column_NA and precedes the level indicators.
Ordered factors are excluded by cols = "auto", but can be selected
explicitly. Original column order and row order are preserved. Input column
names must be unique and non-empty. Encoding that would create duplicate
column names produces an error; rename the relevant columns or factor levels.
The encoding itself requires no additional packages. The data.table
package is required only when the input is a data.table.
A data.frame, or a data.table when the input is a
data.table. Vector and matrix inputs return a data.frame;
a vector is treated as a single column named data.
The input object is not modified.
Reza Mohammadi a.mohammadi@uva.nl
scaler
data(risk)
str(risk)
risk_one_hot <- one.hot(risk, cols = "auto")
str(risk_one_hot)
# Missing values and unused factor levels
example_data <- data.frame(
color = factor(c("red", NA, "blue"), levels = c("blue", "green", "red"))
)
one.hot(example_data, sparsifyNAs = TRUE, naCols = TRUE,
dropCols = TRUE, dropUnusedLevels = TRUE)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.