如何将多因子变量的基类设置为R中最常见的水平?



假设我们有一个包含多个因子变量的数据框架。我们希望运行一个回归,其中每个虚拟类别应该代表不同的组,而不是最常见的组。

如何快速更改所有因子变量的基本类别?

library(titanic) # For titanic data
library(tidyverse)
df <- titanic_train %>% tibble()
df <- df %>% mutate(across(c("Sex", "Pclass", "Embarked"), ~as.factor(.x)))
我们看到基类是C
head(df$Embarked)
#> [1] S C S S S Q
#> Levels:  C Q S

尽管S实际上是最常见的级别

table(df$Embarked)
#> 
#>       C   Q   S 
#>   2 168  77 644

对于Pclass,我们也看到基本类别不是最常见的因子水平:

head(df$Pclass)
#> [1] 3 1 3 1 3 3
#> Levels: 1 2 3
table(df$Pclass)
#> 
#>   1   2   3 
#> 216 184 491

我们如何改变这两个变量,使其在一个整洁的行代码中以最常见的因子级别为基础?

我们可以从这里的forcats包中获取fct_infreq()函数。

df <- df %>% mutate(across(where(is.factor), ~fct_infreq(.x)))

这个应该可以了。再看一下我们上面(非常做作的)例子中的变量:

head(df$Embarked)
#> [1] S C S S S Q
#> Levels: S C Q
table(df$Embarked)
#> 
#>   S   C   Q     
#> 644 168  77   2
head(df$Pclass)
#> [1] 3 1 3 1 3 3
#> Levels: 3 1 2
table(df$Pclass)
#> 
#>   3   1   2 
#> 491 216 184

我们看到基本类别已被正确更改!

最新更新