R:返回前“ n”行并将其余行分组为“其他”行并汇总该列

时间:2018-11-13 12:49:31

标签: r dplyr tidyr

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

我想知道某个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")   

1 个答案:

答案 0 :(得分:0)

以下是我认为可以为您提供所需功能的功能:

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)