用R的help功能发现, 存在
forcats::fct_lump。
因此安装这个包或者tidyverse包,然后library()调用函数。
举个例子。
## Error in `library()`:
## ! there is no package called 'tidyverse'
## Error in `factor(rep(LETTERS[1:9], times = c(40, 10, 5, 27, 1, 1, 1, 1, 1))) %>%
## as.tibble()`:
## ! could not find function "%>%"
## Error:
## ! object 'x' not found
这是样本例子。
## Error in `x %>% distinct()`:
## ! could not find function "%>%"
## Error in `x %>% mutate(value = fct_lump(value)) %>% distinct(value)`:
## ! could not find function "%>%"
这里可以看到x中只有一个column,叫做value。
对这个column进行覆盖,最后level = B, C, E, F, G, H, I → 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确定了被合并的条件。
具体地,
## Error in `factor(letters[rpois(100, 5)]) %>% as.tibble()`:
## ! could not find function "%>%"
## Error:
## ! object 'x' not found
## x
## a b c d e f g h i
## 2 7 15 16 17 20 9 6 7
## Error in `fct_lump(x, n = 3) %>% table()`:
## ! could not find function "%>%"
n = 3表示只能保留三个level,其余都是Other。
## Error in `x %>% table()`:
## ! could not find function "%>%"
## Error in `fct_lump(x, prop = 0.1) %>% table()`:
## ! could not find function "%>%"
prop = 0.1设定了 ≤ 0.1密度的,都是Other。
以上是选多数的,下面可以使得多数分解,少数保留。
## Error in `fct_lump(x, n = -3) %>% table()`:
## ! could not find function "%>%"
## Error in `fct_lump(x, prop = -0.1) %>% table()`:
## ! could not find function "%>%"
可以看到加上了-号后,多数被分解了,临界条件没有变。
最后说下如何批量分箱。
## Error in `data_frame()`:
## ! could not find function "data_frame"
## Error in `z %>% head()`:
## ! could not find function "%>%"
## Error in `z %>% mutate_at(vars(x, y), fct_lump, n = 3) %>% head()`:
## ! could not find function "%>%"
mutate_at中使用vars(x,y)选择需要批量修改的变量,
fct_lump第二个参数就是我们的分箱函数,
n = 3第三个参数就是分箱函数里面的参数,
直线思维,机智的一笔。