forcats包是tidyverse生态中的一个,所以直接加载tidyverse就好了哈
library(tidyverse)
rm(list = ls())
options(stringsAsFactors = T)
#构建因子,默认按照字母顺序
months <- c("Dec","Apr","Jan","Mar")
months <- factor(months);months
#设定因子水平
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)
#按照因子第一次出现的顺序构建水平
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)
## 按照某个函数重新排序
f<- fct_relevel(f, sort);f
## 反转顺序
fct_relevel(f, rev)