Categorical Data Encoding in R
Introduction to Categorical Data
Hello, Space Voyager! Today, we're venturing through fascinating territory: Categorical Data Encoding! Categorical data consists of groups or traits such as gender, marital status, or hometown. We convert categories into numbers using Label and One-Hot Encoding techniques to assist our machine-learning counterparts.
Concept of Label Encoding
Label Encoding maps categories to numbers ranging from 0 through N-1, where N represents the count of unique categories. It's beneficial for ordered data, such as Small, Medium, and Large.
In R, we can achieve this with the help of the factor function. Let's illustrate this with a vector of shirt sizes:
Here, [1] 0 1 2 represents the new numerical values assigned to each size respectively, indicating the encoded values of Small, Medium, and Large as 0, 1, and 2. Levels: 0 1 2 denotes the possible unique values that the factor levels can take after encoding.
To encode a column of categorical data in a data frame, consider the following example:
In this example, we encode the gender column, assigning 1 to Male and 2 to Female.
Concept of One-Hot Encoding
One-Hot Encoding creates additional columns for each category, placing a 1 in the appropriate category and zeros (0) everywhere else. It's preferred for nominal data, where no order is relevant, such as Red, Green, Blue.
The model.matrix function facilitates achieving one-hot encoding in R. This function creates a matrix from a data frame based on a given formula and is useful for one-hot encoding. Key arguments:
- formula:
~ variable - 1, wherevariableis the categorical column and- 1removes the intercept. - data: The data frame containing the specified variable. Here is an example:
For a more complex data frame, consider:
This demonstrates encoding within a data frame that includes multiple columns.
