library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.2 ✔ readr 2.1.4
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ ggplot2 3.4.3 ✔ tibble 3.2.1
## ✔ lubridate 1.9.2 ✔ tidyr 1.3.0
## ✔ purrr 1.0.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(forcats)
# Tạo dữ liệu mẫu
data <- data.frame(
category = factor(c("A", "B", "C", "A", "B")),
value = c(10, 20, 15, 30, 25)
)
# Đổi tên các level của factor
data <- data %>%
mutate(category = fct_recode(category, "Alpha" = "A", "Beta" = "B", "Gamma" = "C"))
print(data)
## category value
## 1 Alpha 10
## 2 Beta 20
## 3 Gamma 15
## 4 Alpha 30
## 5 Beta 25
# Sắp xếp factor theo thứ tự tùy chỉnh
data <- data %>%
mutate(category = fct_inorder(category))
print(data)
## category value
## 1 Alpha 10
## 2 Beta 20
## 3 Gamma 15
## 4 Alpha 30
## 5 Beta 25
# Chuyển factor thành numeric
data <- data %>%
mutate(category = as.numeric(category))
print(data)
## category value
## 1 1 10
## 2 2 20
## 3 3 15
## 4 1 30
## 5 2 25
# Tạo factor từ vector
vec <- c("Low", "Medium", "High", "Low", "Medium")
factor_vec <- as_factor(vec)
print(factor_vec)
## [1] Low Medium High Low Medium
## Levels: Low Medium High
# Tạo factor từ dữ liệu số nguyên
num_vector <- c(2, 1, 3, 1, 2)
factor_num <- as_factor(num_vector)
print(factor_num)
## [1] 2 1 3 1 2
## Levels: 1 2 3