【问题标题】:R: Return the first "n" rows and group the remaining rows into "Other" row and summarise the columnR:返回前“n”行并将剩余行分组为“Other”行并汇总该列
【发布时间】:2018-11-13 12:49:31
【问题描述】:

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

我想知道是否在某些 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")   

【问题讨论】:

    标签: r dplyr tidyr


    【解决方案1】:

    这是一个我认为可以满足你所需要的功能:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      • 2017-12-06
      • 2021-07-07
      • 1970-01-01
      相关资源
      最近更新 更多