forcats包是tidyverse生態(tài)中的一個(gè),所以直接加載tidyverse就好了哈
library(tidyverse)
rm(list = ls())
options(stringsAsFactors = T)
#構(gòu)建因子劫拗,默認(rèn)按照字母順序
months <- c("Dec","Apr","Jan","Mar")
months <- factor(months);months
#設(shè)定因子水平
month_levels <- c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
months1 <- factor(months, levels = month_levels)
months1
#不在你順序中的值變成NA
x1 <- c("Apr","Mar","Jan","Dee")
factor(x1, levels = month_levels)
#按照因子第一次出現(xiàn)的順序構(gòu)建水平
months %>% factor() %>% fct_inorder()
f <- factor(c("a", "b", "c", "d"),
levels = c("b", "c", "d", "a"))
## 把c,d放在地第1位,第2位
fct_relevel(f, c("c", "d"))
# 把`a`放到最后的位置
fct_relevel(f, "a", after = Inf)
## 按照某個(gè)函數(shù)重新排序
f<- fct_relevel(f, sort);f
## 反轉(zhuǎn)順序
fct_relevel(f, rev)