本文介绍了根据 R 中的多列条件查找百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有多个列,我想找出一列在其他列中所占的百分比是相同的.例如;
I have multiple columns and I would like to find the percentage of a one column in the other columns are the same. For example;
ST cd variable
1 1 23432
1 1 2345
1 2 908890
1 2 350435
1 2 2343432
2 1 9999
2 1 23432
所以我想做的是:
如果 ST 和 cd 相同,则求该行的变量占所有具有相同 ST 和 cd 的百分比.所以最后它看起来像:
if ST and cd are the same, then find the percentage of variable for that row over all with the same ST and cd. So in the end it would look like:
ST cd variable percentage
1 1 23432 90.90%
1 1 2345 9.10%
1 2 908890 25.30%
1 2 350435 9.48%
1 2 2343432 65.23%
2 1 9999 29.91%
2 1 23432 70.09%
我怎样才能在 R 中做到这一点?
How can I do this in R?
感谢大家的帮助.
推荐答案
您可以创建您的比例格式功能:
You can create your proportion format function:
prop_format <-
function (x, digits=4)
{
x <- round(x/sum(x), digits)*100
paste0(x,'%')
}
然后使用 ave
:
ave(dt$variable,list(dt$ST,dt$cd),FUN=prop_format)
[1] "90.9%" "9.1%" "25.23%" "9.73%" "65.05%" "29.91%" "70.09%"
这篇关于根据 R 中的多列条件查找百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!