r - 将具有非常小的行总和的行合并到一个新的组合行中
问题描述
在这个数据集中,两个分类单元(在行中)对整体数据的贡献很小,我想收集所有这些行,它们的行和小于整个数据集的 n%。n 可以是 1, 2, 3...
df <- data.frame(A=c(1000,100,1,0), B=c(100,1000,1,1), C=c(10,900,0,1))
row.names(df) <- c("Tax1", "Tax2", "Tax3", "Tax4")
> df
A B C
Tax1 1000 100 10
Tax2 100 1000 900
Tax3 1 1 0
Tax4 0 1 1
在识别出这些低和行之后,我想将它们分类为例如“其他”:
> df
A B C
Tax1 1000 100 10
Tax2 100 1000 900
Other 1 2 1
谢谢!
解决方案
#Set n
n <- 0.1 #10%
#Calculate proportions of their row sums
rows <- prop.table(rowSums(df)) < n
#combine the rows and add a new row with 'Other'
rbind(df[!rows, ], Other = colSums(df[rows, ]))
# A B C
#Tax1 1000 100 10
#Tax2 100 1000 900
#Other 1 2 1
推荐阅读
- android - 由于违反权限政策,我的 SMS Transfer 相关应用被拒绝
- javascript - 如何处理破坏我的网站的 Firefox 插件?
- android - 将相机添加到 Android Fragment 中,如 Instagram 帖子上传
- strapi - Strapi:什么是内容和 API 迁移策略
- c# - 使用 Autofac 时激活特定注册时出错
- node.js - PM2安装不生成脚本
- c# - 使用 NSubstitute 进行依赖注入
- java - Spring Boot URL 请求映射返回 NullPointerException
- python - 如何在python中将包含unicode字符的字符串转换为UTF?
- reactjs - 有没有办法在“react-pdf”中添加表格?