【问题标题】:R Dplyr top_n does not work when used within functionR Dplyr top_n 在函数中使用时不起作用
【发布时间】:2017-09-14 20:30:04
【问题描述】:

我的 dplyr 函数是这样的

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 然而事实并非如此。

使用下面的函数(top_n 没有 interp),我得到了一个结果,但是我没有看到所需的前 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")

}

有什么想法吗?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    我的解决方案,从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))
    
    }
    

    如果有人有更有效的方法,请分享

    【讨论】:

      猜你喜欢
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 2016-04-01
      • 2020-04-04
      • 2020-08-24
      • 2019-06-08
      相关资源
      最近更新 更多