{r setup, include=FALSE} knitr::opts_chunk$set(eval = FALSE) 用R的help功能发现, 存在 forcats::fct_lump。 因此安装这个包或者tidyverse包,然后library()调用函数。
举个例子。
{r message=FALSE, warning=FALSE} library(tidyverse)
{r} x <- factor(rep(LETTERS[1:9], times = c(40, 10, 5, 27, 1, 1, 1, 1, 1))) %>% as.tibble() # x %>% head() # x %>% str() table(x)
这是样本例子。
{r} x %>% distinct() x %>% mutate(value = fct_lump(value)) %>% distinct(value)
这里可以看到x中只有一个column,叫做value。 对这个column进行覆盖,最后$level = B, C, E, F, G, H, I \to Other$。
作用过程如下:
fct_lump(f, n, prop, other_level = "Other", ties.method = c("min",
"average", "first", "last", "random", "max"))
other_level = "Other"决定了合并level的新命名,默认为Other,这里可以修改的。
其中n, prop确定了被合并的条件。
具体地,
{r} x <- factor(letters[rpois(100, 5)]) %>% as.tibble() x
{r} x <- factor(letters[rpois(100, 5)]) table(x)
{r} fct_lump(x, n = 3) %>% table()
n = 3表示只能保留三个level,其余都是Other。
{r} x %>% table()/length(x) fct_lump(x, prop = 0.1) %>% table()/length(x)
prop = 0.1设定了$\leq 0.1$密度的,都是Other。
以上是选多数的,下面可以使得多数分解,少数保留。
{r} fct_lump(x, n = -3) %>% table()/length(x) fct_lump(x, prop = -0.1) %>% table()/length(x)
可以看到加上了-号后,多数被分解了,临界条件没有变。
最后说下如何批量分箱。
{r} z = data_frame( `x` = x, `y` = x ) z %>% head()
{r} z %>% mutate_at(vars(x,y), fct_lump, n = 3) %>% head()
mutate_at中使用vars(x,y)选择需要批量修改的变量, fct_lump第二个参数就是我们的分箱函数, n = 3第三个参数就是分箱函数里面的参数, 直线思维,机智的一笔。