将行和非常小的行合并到一个新的组合行中

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


以上是将行和非常小的行合并到一个新的组合行中的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>