2
我想仅保留基于频率的前两个因子水平并将所有其他因子分组到其他因子中。我试过这个,但它没有帮助。基于数据的数据框中的所有因子变量的折叠因子水平
df=data.frame(a=as.factor(c(rep('D',3),rep('B',5),rep('C',2))),
b=as.factor(c(rep('A',5),rep('B',5))),
c=as.factor(c(rep('A',3),rep('B',5),rep('C',2))))
myfun=function(x){
if(is.factor(x)){
levels(x)[!levels(x) %in% names(sort(table(x),decreasing = T)[1:2])]='Others'
}
}
df=as.data.frame(lapply(df, myfun))
期望输出
a b c
D A A
D A A
D A A
B A B
B A B
B B B
B B B
B B B
others B others
others B others
你想计算整个数据框或列的因子频率?请分享您的预期输出。 –
它只会是一个变量,我只保留基于频率的前2个因子,并将其他所有其他级别组合在一起。 –
鉴于上述数据框,您可以添加预期输出吗? – thepule