2016-08-05 66 views
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 
+0

你想计算整个数据框或列的因子频率?请分享您的预期输出。 –

+0

它只会是一个变量,我只保留基于频率的前2个因子,并将其他所有其他级别组合在一起。 –

+0

鉴于上述数据框,您可以添加预期输出吗? – thepule

回答

2

这可能会有点凌乱,但在这里是通过基础R一种方法,

fun1 <- function(x){levels(x) <- 
        c(names(sort(table(x), decreasing = TRUE)[1:2]), 
        rep('others', length(levels(x))-2)); 
        return(x)} 

然而上述功能需要先进行重新有序和作为OP国家在评论中,正确的将是,

fun1 <- function(x){ x=factor(x, 
        levels = names(sort(table(x), decreasing = TRUE))); 
        levels(x) <- c(names(sort(table(x), decreasing = TRUE)[1:2]), 
        rep('others', length(levels(x))-2)); 
        return(x) } 
0

这从forcats包装中获得fct_lump()现在很容易。

fct_lump(df$a, n = 2) 

# [1] D  D  D  B  B  B  B  B  Other Other 
# Levels: B D Other 

的论点n控制最常见的级别数被保存下来,其他人混为一谈。

相关问题