2017-09-14 147 views
1

我dplyr功能看起來像這樣[R Dplyr top_n不起作用

convert_to_top5_df=function(df) 

{ 
    require(dplyr) 
    require(lazyeval) 
    require(tidyr) 

    df %>% 
    filter(!is.na(SVM_LABEL_QOL)) %>%   
    select(globalsegment,Account,SVM_LABEL_QOL) %>% 
    group_by(globalsegment,Account) %>% 
    summarise_(QoL=interp(~round(sum(SVM_LABEL_QOL %in% 'QoL')/n(),2))) %>% 
    ungroup(globalsegment,Account) %>% 
    arrange(desc(QoL)) %>% 
    interp(~top_n(5,wt = "QoL")) 

} 

我加了interp說法,因爲我認爲這個問題是由於lazyeval 然而,這並非如此。

使用下面的函數(沒有interptop_n),我得到一個結果,但是我沒有看到前5個結果。

閱讀其他stackoverflow帖子,我知道這與ungroup,但不知道如何實現這一點。

convert_to_top5_df=function(df) 

{ 
    require(dplyr) 
    require(lazyeval) 
    require(tidyr) 

    df %>% 
    filter(!is.na(SVM_LABEL_QOL)) %>% 
    select(globalsegment,Account,SVM_LABEL_QOL) %>% 
    group_by(globalsegment,Account) %>% 
    summarise_(QoL=interp(~round(sum(SVM_LABEL_QOL %in% 'QoL')/n(),2))) %>% 
    ungroup(globalsegment,Account) %>% 
    arrange(desc(QoL)) %>% 
    top_n(5,wt = "QoL") 

} 

任何想法?

回答

0

我solutionn,從QoL取出倒報價,並添加一個額外的參數arrange

#Function to convert dataframe for pie chart analysis (Global) 
convert_to_top5_df=function(df) 

{ 

require(dplyr) 
require(lazyeval) 
require(tidyr) 

df %>% 
filter(!is.na(SVM_LABEL_QOL)) %>%   
select(globalsegment,Account,SVM_LABEL_QOL) %>% 
group_by(globalsegment,Account) %>% 
summarise_(QoL=interp(~round(sum(SVM_LABEL_QOL %in% 'QoL')/n(),2))) %>% 
top_n(5,QoL) %>% 
arrange(globalsegment,desc(QoL)) 

} 

如果任何人有一個更有效的方式,請分享