f <- factor(sample(letters[1:3], 20, replace = TRUE))
f
#增加因子水平
fct_expand(f, "d", "e", "f")
#自動刪除沒用的因子水平
f <- factor(c("a", "b"), levels = c("a", "b", "c","1"))
f
fct_drop(f)
#給 NA 一個水平漱竖,確保畫圖或匯總的時候能用上
f1 <- factor(c("a", "a", NA, NA, "a", "b", NA, "c", "a", "c", "b"))
fct_count(f1)
f2 <- fct_explicit_na(f1, na_level = "missing")
fct_count(f2)
#這個函數(shù)是作用于列表的,用于統(tǒng)一列表內(nèi)的因子水平
fs <- list(factor("a"),
factor("b"),
factor(c("a", "b")))
fct_unify(fs, levels = c("a", "b", "c"))
fruit <- factor(c("apple", "kiwi", "apple", "apple"))
colour <- factor(c("green", "green", "red", "green"))
fct_cross(fruit, colour)
x <- c("a", "z", "g")
as.factor(x) # 會改變順序
## [1] a z g
## Levels: a g z
as_factor(x) # 還是按照原來的順序
## [1] a z g
## Levels: a z g
#檢查是否存在某個因子
table(fct_match(gss_cat$marital, c("Married", "Divorced")))
代碼塊
代碼塊
代碼塊
代碼塊
代碼塊
代碼塊
代碼塊
代碼塊