Suppose we have a data frame as follows:
1 2 3 4 5 6 |
##### Creating Sample Data ##### Availability <- c(10,5,20,15,30,25) Size <- factor(c("S","XS","L","M","XXL","XL")) Category <- factor(c("Jeans","Hoodie","Shorts","Pants","Sweaters","Socks")) (data <- data.frame(Availability, Size, Category)) |
1 2 3 4 5 6 7 8 |
> (data <- data.frame(Availability, Size, Category)) Availability Size Category 1 10 S Jeans 2 5 XS Hoodie 3 20 L Shorts 4 15 M Pants 5 30 XXL Sweaters 6 25 XL Socks |
Looks good. But here is the issue
1 |
data$Size |
1 2 3 |
> data$Size [1] S XS L M XXL XL Levels: L M S XL XS XXL |
It is sorted alphabetically, which might not be the best in this case. We can use ordered() to create an ordered factor variable.
1 2 |
data2 <- data (data2$Size <- ordered(data2$Size, levels = c("XS","S","M","L","XL","XXL"))) |
1 2 3 |
> (data2$Size <- ordered(data2$Size, levels = c("XS","S","M","L","XL","XXL"))) [1] S XS L M XXL XL Levels: XS < S < M < L < XL < XXL |
But in case of Category, it is sorted alphabetically by default. But if we want to change its order, we can use factor() .
1 |
(data2$Category <- factor(data2$Category, levels = c("Jeans","Pants","Shorts", "Hoodie", "Sweaters","Socks"))) |
1 2 3 4 |
> (data2$Category <- factor(data2$Category, levels = c("Jeans","Pants","Shorts", "Hoodie", "Sweaters","Socks"))) [1] Jeans Hoodie Shorts Pants Sweaters Socks Levels: Jeans Pants Shorts Hoodie Sweaters Socks |