首页 > 解决方案 > R:返回前“n”行并将剩余行分组为“Other”行并汇总该列

问题描述

我是巴西人,对不起我的英语!

我想知道是否在某些 R 包中实现了一个函数来过滤前“n”行并将剩余的行分组为“其他”行并汇总列。

下面是我想要的示例:

library(tidyverse)
library(plotly)
library(scales)  
data("lakers")

x = bind_rows(  
lakers %>% count(player) %>% arrange(-n) %>% head(10),  
lakers %>% count(player) %>% arrange(-n) %>% slice(11:n()) %>%  
summarise(player = "Others", n = sum(n))) %>%  
  filter(!player == "") %>%  
  mutate(
    player = factor(player, levels = rev(.$player)))

ggplot(x, aes(x=player, y=n))+  
  geom_col(fill = "DodgerBlue1", col = "DodgerBlue3")+  
  coord_flip()+  
  geom_text(aes(y=n, label = comma(n)),hjust = -.2)+  
  scale_y_continuous(limits = c(0, max( x$n*1.1 )))+  
  theme_minimal()

我需要创建一个这样的ggplot。所以我有一个使用 dplyr 的大查询,我不想每次都重复查询。

我想要一些功能,例如:

head.other(x, rows = 20, fun = sum, name = "Others")   

标签: rdplyrtidyr

解决方案


这是一个我认为可以为您提供所需的功能:

library(tibble)
library(dplyr)

df <- data.frame(col1 = rnorm(10), col2 = rnorm(10)) # your data frame
n <- 6 # top n rows to keep

myfun <- function(df, n) {

  # seperate keep rows and those to aggregate
  preserve.df <- df[1:n, ]
  summarise.df <- df[(n+1):nrow(df), ]

  # create new df in required format
  new.df <- bind_rows(preserve.df, sapply(summarise.df, sum))

  # add a column to identify the rows and return
  rownames(new.df) <- c(paste0("r", 1:n), "Other")
  rownames_to_column(new.df)
}

myfun(df, 6)

推荐阅读