首页 > 解决方案 > 将具有非常小的行总和的行合并到一个新的组合行中

问题描述

在这个数据集中,两个分类单元(在行中)对整体数据的贡献很小,我想收集所有这些行,它们的行和小于整个数据集的 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

谢谢!

标签: r

解决方案


#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

推荐阅读