library(tidyverse)
rm(list = ls())
options(stringsAsFactors = T)
#構(gòu)建測試數(shù)據(jù)集
df <- forcats::gss_cat%>%
select(c("rincome", "denom"))
head(df,3)
# 對df的每一列都使用`levels()`函數(shù)
lapply(df, levels)
#查看每列分類分布個數(shù)
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"都被排在最后了
# 3. 按照因子因素進(jìn)行排序----------------------------------------------------------------------
# fct_inorder(): 按照第一次出現(xiàn)的順序
#
# fct_infreq(): 按照每個水平出現(xiàn)的頻率(從大到凶拭獭)
#
# fct_inseq(): 按照數(shù)字大小
f <- factor(c("b", "b", "a", "c", "c", "c"))
f #默認(rèn)按字母順序
fct_inorder(f) # 按第一次出現(xiàn)的順序
第一次出現(xiàn)的順序一般沒啥意義,所以覺得不太實(shí)用
fct_infreq(f) # 按出現(xiàn)的頻率從大到小排列
一般經(jīng)常以頻率最高的為參考組炕吸,所以這個功能比較有用
f <- factor(1:3, levels = c("3", "2", "1"))
fct_inseq(f) # 按照數(shù)字順序排列,雖然你定義的順序是"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函數(shù)操作,按照其他列順序進(jìn)行操作----------------------------------------------------------------------
#生成一個簡單的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已經(jīng)變了
fct_reorder(df$color, df$a, min)
#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)
#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")
#將因子水平左右移動,默認(rèn)向左移
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)#向右移動