使用forcats处理因子
11.1 简介
因子在 R 中用于处理分类变量。分类变量是在固定的已知集合中取值的变量。当想要以非字母表顺序显示字符向量时,也可以使用分类变量。
我们将使用 forcats 包来处理因子,这个包提供了能够处理分类变量(其实就是因子的另一种说法)的工具,其中还包括了处理因子的大量辅助函数。
library(tidyverse) library(forcats)
11.2 创建因子
假设我们想要创建一个记录月份的变量:
x1 <- c("Dec", "Apr", "Jan", "Mar")
使用字符串来记录月份有两个问题。
月份只有 12 个取值,如果输入错误,那么代码不会有任何反应。
对月份的排序没有意义。
sort(x1) > [1] "Apr" "Dec" "Jan" "Mar"
你可以通过使用因子来解决以上两个问题。要想创建一个因子,必须先创建有效水平的一 个列表:
month_levels <- c( "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
现在可以创建因子了:
x1 <- c("Dec", "Apr", "Jan", "Mar") y1 <- factor(x1, levels = month_levels) y1 > y1 [1] Dec Apr Jan Mar 12 Levels: Jan Feb Mar Apr May Jun Jul Aug Sep ... Dec sort(y1) > sort(y1) [1] Jan Mar Apr Dec 12 Levels: Jan Feb Mar Apr May Jun Jul Aug Sep ... Dec
不在有效水平集合内的所有值都会自动转换为 NA:
x2 <- c("Dec", "Apr", "Jam", "Mar") y2 <- factor(x2, levels = month_levels) > y2 [1] Dec Apr <NA> Mar 12 Levels: Jan Feb Mar Apr May Jun Jul Aug Sep ... Dec
如果想要显示错误信息,那么你可以使用 readr::parse_factor() 函数:
y2 <- parse_factor(x2, levels = month_levels) > y2 <- parse_factor(x2, levels = month_levels) Warning: 1 parsing failure. row col expected actual 3 -- value in level set Jam
如果省略了定义水平的这个步骤,那么会将按字母顺序排序的数据作为水平:
> factor(x1) [1] Dec Apr Jan Mar Levels: Apr Dec Jan Mar
如果想让因子的顺序与初始数据的顺序保持一致。在创建因子时,将水平设置为 unique(x),或者在创建因子后再对其使用 fct_inorder() 函数,就可以达到这个目的:
f1 <- factor(x1, levels = unique(x1)) f1 > [1] Dec Apr Jan Mar > Levels: Dec Apr Jan Mar f2 <- x1 %>% factor() %>% fct_inorder() f2 > [1] Dec Apr Jan Mar > Levels: Dec Apr Jan Mar
如果想要直接访问因子的有效水平集合,那么可以使用 levels() 函数:
levels(f2) > [1] "Dec" "Apr" "Jan" "Mar"
11.3 综合社会调查
gss_cat 时包里自带的数据集中,这里用来说明处理因子时经常遇到的一些问题:
gss_cat > gss_cat # A tibble: 21,483 x 9 year marital age race rincome partyid relig <int> <fct> <int> <fct> <fct> <fct> <fct> 1 2000 Never ~ 26 White $8000 ~ Ind,ne~ Prot~ 2 2000 Divorc~ 48 White $8000 ~ Not st~ Prot~ 3 2000 Widowed 67 White Not ap~ Indepe~ Prot~ 4 2000 Never ~ 39 White Not ap~ Ind,ne~ Orth~ 5 2000 Divorc~ 25 White Not ap~ Not st~ None 6 2000 Married 25 White $20000~ Strong~ Prot~ 7 2000 Never ~ 36 White $25000~ Not st~ Chri~ 8 2000 Divorc~ 44 White $7000 ~ Ind,ne~ Prot~ 9 2000 Married 44 White $25000~ Not st~ Prot~ 10 2000 Married 47 White $25000~ Strong~ Prot~ # ... with 21,473 more rows, and 2 more variables: # denom <fct>, tvhours <int>
当因子保存在 tibble 中时,其水平不是很容易看到的。查看因子水平的一种方法是使用 count() 函数:
gss_cat %>% count(race) > gss_cat %>% + count(race) # A tibble: 3 x 2 race n <fct> <int> 1 Other 1959 2 Black 3129 3 White 16395
或者使用条形图:
ggplot(gss_cat, aes(race)) + geom_bar()
默认情况下,ggplot2 会丢弃没有任何数据的那些水平,可以使用以下代码来强制显示这些水平:
ggplot(gss_cat, aes(race)) + geom_bar() + scale_x_discrete(drop = FALSE)
11.4 修改因子水平
比修改因子水平顺序更强大的操作是修改水平的值。修改水平不仅可以使得图形标签更美 观清晰,以满足出版发行的要求,还可以将水平汇集成更高层次的显示。修改水平最常用、最强大的工具是 fct_recode() 函数,它可以对每个水平进行修改或重新编码。
例如, 我们看一下 gss_cat$partyid:
gss_cat %>% count(partyid) > gss_cat %>% count(partyid) # A tibble: 10 x 2 partyid n <fct> <int> 1 No answer 154 2 Don't know 1 3 Other party 393 4 Strong republican 2314 5 Not str republican 3032 6 Ind,near rep 1791 7 Independent 4119 8 Ind,near dem 2499 9 Not str democrat 3690 10 Strong democrat 3490
对水平的描述太过简单,而且不一致。我们将其修改为较为详细的排比结构:
gss_cat %>% mutate(partyid = fct_recode(partyid, "Republican, strong" = "Strong republican", "Republican, weak" = "Not str republican", "Independent, near rep" = "Ind,near rep", "Independent, near dem" = "Ind,near dem", "Democrat, weak" = "Not str democrat", "Democrat, strong" = "Strong democrat" )) %>% count(partyid) ># A tibble: 10 x 2 partyid n <fct> <int> 1 No answer 154 2 Don't know 1 3 Other party 393 4 Republican, strong 2314 5 Republican, weak 3032 6 Independent, near rep 1791 7 Independent 4119 8 Independent, near dem 2499 9 Democrat, weak 3690 10 Democrat, strong 3490
fct_recode() 会让没有明确提及的水平保持原样,如果不小心修改了一个不存在的水平, 那么它也会给出警告。
可以将多个原水平赋给同一个新水平,这样就可以合并原来的分类:
gss_cat %>% mutate(partyid = fct_recode(partyid, "Republican, strong" = "Strong republican", "Republican, weak" = "Not str republican", "Independent, near rep" = "Ind,near rep", "Independent, near dem" = "Ind,near dem", "Democrat, weak" = "Not str democrat", "Democrat, strong" = "Strong democrat", "Other" = "No answer", "Other" = "Don't know", "Other" = "Other party" )) %>% count(partyid) > # A tibble: 8 x 2 partyid n <fct> <int> 1 Other 548 2 Republican, strong 2314 3 Republican, weak 3032 4 Independent, near rep 1791 5 Independent 4119 6 Independent, near dem 2499 7 Democrat, weak 3690 8 Democrat, strong 3490
如果想要合并多个水平,那么可以使用 fct_recode() 函数的变体 fct_collapse() 函数。对于每 个新水平,你都可以提供一个包含原水平的向量:
gss_cat %>% mutate(partyid = fct_collapse(partyid, other = c("No answer", "Don't know", "Other party"), rep = c("Strong republican", "Not str republican"), ind = c("Ind,near rep", "Independent", "Ind,near dem"), dem = c("Not str democrat", "Strong democrat") )) %>% count(partyid) > # A tibble: 4 x 2 partyid n <fct> <int> 1 other 548 2 rep 5346 3 ind 8409 4 dem 7180