r - 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")
解决方案
这是一个我认为可以为您提供所需的功能:
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)
推荐阅读
- php - 将 JPG 转换为 PNG 和压缩的问题 | PHP
- java - 如何用下一页“10 项”填充标题和网格布局
- swift - if(变量赋值)语法查询(Swift)
- java - 我想知道为什么 youtube 播放器没有在 hadler (Android Studio) 中重新启动
- c# - .NET 中的 SOA 实现和部署
- android - 如何使用 viewmodel mvvm 在 Android 中保留自定义视图的数据?
- laravel - 用于 postgres 工作查询的相关 laravel 查询
- git - 如何将来自分支的稍后提交合并到 master 丢弃一些早期的更改?
- python - user_passes_test 用于 Django 中除 User 之外的模型
- angular - NgRx RxJS 提取和重用公共选择器