gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:11:20 24 4
gpt4 key购买 nike

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

关于r - 将行和非常小的行合并到一个新的组合行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67835569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com