R语言

R-tidyverse系列-forcats处理因子

2020-06-14  本文已影响0人  小贝学生信

目前所学知识里,主要需要用到factor因子的地方就是绘图时(例如箱线图)用于调整顺序。forcats提供了一些便捷函数用于调整factor的levels顺序

1、基础函数

test = factor(c("c","b","c"))
test
# [1] c b c
# Levels: b c
levels(test)
# [1] "b" "c"

factor(c("c","b","c"), levels = c("c","b"))
# [1] c b c
# Levels: c b

2、forcats包调整因子顺序

首先forcats包本身提供了关于factor多种多样的处理技巧,这里仅提及学习其中关于因子顺序的相关函数。

2.1 根据向量本身特点修改levels

f <- factor(c("a", "c", "b", "a"),
        levels = c("a", "b", "c"))
fct_relevel(f, c("b", "c", "a"))
# [1] a c b a
# Levels: b c a
f <- factor(c("b", "c", "c", "b","a","b"))
fct_infreq(f)
# [1] b c c b a b
# Levels: b c a
f <- factor(c("b", "c", "c", "a","b","a"))
fct_inorder(f)
# [1] b c c a b a
# Levels: b c a
f <- factor(c("b", "c", "c", "a","b","a"))
fct_rev(f)
# [1] b c c a b a
# Levels: c b a

2.2 根据向量相关属性(data.frame)指标修改levels

iris示例数据为例

data("iris")

summary(iris)
# Sepal.Length    Sepal.Width     Petal.Length    Petal.Width          Species  
# Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100   setosa    :50  
# 1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300   versicolor:50  
# Median :5.800   Median :3.000   Median :4.350   Median :1.300   virginica :50  
# Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199                  
# 3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800                  
# Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500        

str(iris)
# 'data.frame': 150 obs. of  5 variables:
#   $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
# $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
# $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
# $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
# $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

levels(iris$Species)
# [1] "setosa"     "versicolor" "virginica"         

fct_reorder()

fct_reorder(iris$Species, iris$Sepal.Width) %>% levels()
# [1] "versicolor" "virginica"  "setosa"

aggregate(iris$Sepal.Width, by=list(iris$Species), mean)
#     Group.1     x
# 1     setosa 3.428
# 2 versicolor 2.770
# 3  virginica 2.974
#aggregate(iris$Sepal.Width, by=list(iris$Species), median)
fct_reorder(iris$Species, iris$Sepal.Width, median, .desc=T) %>% levels()
p1=ggplot(iris, aes(x=Species, y=Sepal.Width)) +
    geom_boxplot() +
    ggtitle("default factor levels")
p2=ggplot(iris, aes(x=fct_reorder(Species, Sepal.Width), y=Sepal.Width)) +
    geom_boxplot() +
    ggtitle("fct_reorder default levels")
p3=ggplot(iris, aes(x=fct_reorder(Species, Sepal.Width, .desc=T), y=Sepal.Width)) +
    geom_boxplot() +
    ggtitle("fct_reorder descent levels")
library(patchwork)
p1 | p2 | p3
上一篇下一篇

猜你喜欢

热点阅读