代码之家  ›  专栏  ›  技术社区  ›  delcast

top_n()未选择n

  •  0
  • delcast  · 技术社区  · 7 年前

    目的:按降序排列前20个国家

    问题:使用 top_n 功能,它坚持选择所有,而不仅仅是前20名。

    这是我的代码:

    #Omit missing values
    na.omit(kiva_loans)%>%
      #Group by country label
      group_by(country_code)%>%
      dplyr::count(country_code, sort = TRUE)%>%
      top_n(20)%>%
       ggplot(aes(reorder(x=country_code,n),y=n))+
       geom_col(position="dodge",
                color = "black",
                fill="purple")+
       coord_flip()
    

    之后 top_n(20) 行,输出为:

    enter image description here

    这表明它不会在20岁的时候断掉。这又是一个可怕的阴谋:

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  2
  •   RLave    7 年前
    #Omit missing values
    na.omit(kiva_loans)%>%
      #Group by country label
      group_by(country_code)%>%
      dplyr::count(country_code, sort = TRUE)%>%
      ungroup() %>% # add thia to ungroup
      top_n(20)%>%
       ggplot(aes(reorder(x=country_code,n),y=n))+
       geom_col(position="dodge",
                color = "black",
                fill="purple")+
       coord_flip()
    

    只是 ungroup() 在你打电话之前 top_n

    ?top_n 您可以阅读以下内容:

    n要返回的行数。如果x被分组,这是每个组的行数。如果有关联,将包含超过n行。

    推荐文章