library(tidyverse)
rm(list = ls())
options(stringsAsFactors = T)
#计算每个因子的数量
gss_cat$relig %>% fct_count(prop = T,sort = T)
fct_count(gss_cat$partyid)
partyid2 <- fct_collapse(gss_cat$partyid,
missing = c("No answer", "Don't know"),
rep = c("Strong republican", "Not str republican"),
other = "Other party",
ind = c("Ind,near rep", "Independent", "Ind,near dem"),
dem = c("Not str democrat", "Strong democrat")
)
fct_count(partyid2)
#fct_lump()是一系列函数,可以将满足某些条件的水平合并为一组。
# fct_lump_min(): 把小于某些次数的归为其他类.
#
# fct_lump_prop(): 把小于某个比例的归为其他类.
#
# fct_lump_n(): 把个数最多的n个留下,其他的归为一类(如果n < 0,则个数最少的n个留下).
#
# fct_lump_lowfreq(): 将最不频繁的级别合并在一起.
x <- factor(rep(LETTERS[1:9],
times = c(40, 10, 5, 27, 1, 1, 1, 1, 1)))
x %>% table()
#把个数最多的3个留下,其他归为一类
x %>% fct_lump_n(3) %>% table()
#把个数最少的3个留下
x %>% fct_lump_n(-3) %>% table()
#把比例小于0.1的归为一类
x %>% fct_lump_prop(0.1) %>% table()
感觉这个最有用了 ,这个比例不应该超过其他各组的比例
#把小于2次的归为其他类
x %>% fct_lump_min(2, other_level = "其他") %>% table()
#fct_lump_lowfreq() lumps together the least frequent levels, ensuring that "other" is still the smallest level.
x %>% fct_lump_lowfreq() %>% table()
这个可以实现fct_lump_prop的功能,但是结果不可设定,还是prop好
#把某些因子归为其他类,类似于 fct_lump
x <- factor(rep(LETTERS[1:9], times = c(40, 10, 5, 27, 1, 1, 1, 1, 1)))
# 把A,B留下,其他归为一类
fct_other(x, keep = c("A", "B"), other_level = "other")
# 把A,B归为一类,其他留下
fct_other(x, drop = c("A", "B"), other_level = "lx")
x <- factor(c("apple", "bear", "banana", "dear"))
x
fct_recode(x, fruit = "apple", fruit = "banana")
fct_recode(x, NULL = "apple", fruit = "banana")
gss_cat$partyid %>% fct_count()
#批量替换一列分类中的名称
gss_cat$partyid %>%
fct_relabel(~ gsub(",", "++", .x)) %>%
fct_count()