library(tidyverse)
rm(list = ls())
options(stringsAsFactors = T)
#构建测试数据集
df <- forcats::gss_cat%>%
select(c("rincome", "denom"))
head(df,3)

数据集情况
# 对df的每一列都使用`levels()`函数
lapply(df, levels)

查看每列的分类情况
#查看每列分类分布个数
lapply(df,fct_count)

这个功能比较好,能看到个数分布情况
#查看每列分类分布比例
lapply(df,fct_count,prop = T)

这个功能更好了,可以看到分布比例小于0.1的变量
# 对df的每一列使用`fct_relevel(..., "Don't know", after = Inf)`
df2 <- lapply(df, fct_relevel, "Don't know", after = Inf)
lapply(df2, levels) # 可以看到"Don't know"都被排在最后了

批量relevel感觉可能不太实用
# 3. 按照因子因素进行排序----------------------------------------------------------------------
# fct_inorder(): 按照第一次出现的顺序
#
# fct_infreq(): 按照每个水平出现的频率(从大到小)
#
# fct_inseq(): 按照数字大小
f <- factor(c("b", "b", "a", "c", "c", "c"))
f #默认按字母顺序

默认按照字母顺序要牢记
fct_inorder(f) # 按第一次出现的顺序

第一次出现的顺序一般没啥意义,所以觉得不太实用
fct_infreq(f) # 按出现的频率从大到小排列

一般经常以频率最高的为参考组,所以这个功能比较有用
f <- factor(1:3, levels = c("3", "2", "1"))
fct_inseq(f) # 按照数字顺序排列,虽然你定义的顺序是"3", "2", "1"

按照从小到大的顺序排序
#绘图展示
starwars%>%
filter(!is.na(hair_color))%>%
ggplot(aes(x = hair_color,fill = hair_color))+
geom_bar() +
coord_flip()

原始图,删除缺失是因为缺失会始终排在第一个
#按照频率排序
starwars%>%
filter(!is.na(hair_color))%>%
ggplot(aes(x = fct_infreq(hair_color),fill = hair_color))+
geom_bar() +
coord_flip()

按照频率排序,看这里顺多了
# 4. reorder函数操作,按照其他列顺序进行操作----------------------------------------------------------------------
#生成一个简单的tibble
df <- tibble::tribble(
~color, ~a, ~b,
"blue", 1, 2,
"green", 6, 2,
"purple", 3, 3,
"red", 2, 3,
"yellow", 5, 1
)

模拟数据集
df$color <- factor(df$color)
df$color

默认顺序
# 按照a这一列从小到大的顺序,排序color这一列,
# 可以看到color的levels已经变了
fct_reorder(df$color, df$a, min)

按照a列的大小对颜色列进行排序
#fct_reorder()用于画图小例子
boxplot(Sepal.Width ~ Species, data = iris)
boxplot(Sepal.Width ~ fct_reorder(Species, Sepal.Width), data = iris)
boxplot(Sepal.Width ~ fct_reorder(Species, Sepal.Width, .desc = TRUE), data = iris)

原始图像

按照Y轴排序

降序排序
#fct_reorder2的例子
chks <- subset(ChickWeight, as.integer(Chick) < 10)
chks <- transform(chks, Chick = fct_shuffle(Chick))
chks

数据集
ggplot(chks, aes(Time, weight, colour = Chick)) +
geom_point() +
geom_line()

原始图片
# 图例的顺序和线的顺序一样
ggplot(chks, aes(Time, weight, colour = fct_reorder2(Chick, Time, weight))) +
geom_point() +
geom_line() +
labs(colour = "Chick")

顺序一样了,其实我也不太理解
#将因子水平左右移动,默认向左移
x <- factor(
c("Mon", "Tue", "Wed"),
levels = c("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"),
ordered = TRUE
)
x

原始因子水平
fct_shift(x)

默认移动到最左侧
fct_shift(x, 2)

移动超过边界后会从最后再开始
fct_shift(x, -1)#向右移动

这个有用
网友评论