在这份销售报告中,有一个特定的资金池需要按不同的百分比(总和为100%)分配给六个组.然而,由于需要进行会计四舍五入,根据总数的不同,经常会有几分钱的差异.
例如:
# TOTAL
total <- 12345.02
# PERCENT ALLOCATIONS
perA <- .12
perB <- .23
perC <- .22
perD <- .13
perE <- .11
perF <- .19
# ALLOCATIONS
amtA <- total * perA
amtB <- total * perB
amtC <- total * perC
amtD <- total * perD
amtE <- total * perE
amtF <- total * perF
这些计算是正确的,但当采用accounting
时,如预期的那样,将需要四舍五入到小数点后两位,在此期间,并非所有资金都得到分配.
结果:
library(formattable)
accounting(amtA) = $ 1,481.40
accounting(amtB) = $ 2,839.35
accounting(amtC) = $ 2,715.90
accounting(amtD) = $ 1,604.85
accounting(amtE) = $ 1,357.95
accounting(amtF) = $ 2,345.55
-----------------------------
sum = $12,345.00 =/= $12,345.02
我本质上想知道是否有一种简单的方法来判断四舍五入分配的总和与原始总数,处理四舍五入的数字而不考虑精度.从这里开始,如果需要,按特定顺序(E、A、C、B、D、F)分配任何剩余资金.
因为我知道哪个更改将导致错误,因为我的6&;百分比组是静态的,所以我有一个简单的方法来判断总数,如果它以问题 case 结束,并设置应用它的规则.
library(dplyr)
library(stringr)
# OFF BY ONE CENT THAT NEEDS ALLOCATED
singlepos <- c("01","18",...)
# OFF BY TWO CENTS THAT NEED ALLOCATED
doublepos <- c("02","98",...)
# OFF BY ONE CENT THAT NEEDS UNALLOCATED
singleneg <- c("07","08",...)
amtE <- round(total * perE,2)
amtE <- case_when(
str_sub(as.character(amtE), starts = -2) %in% singlepos ~ amtE+.01,
str_sub(as.character(amtE), starts = -2) %in% doublepos ~ amtE+.01,
str_sub(as.character(amtE), starts = -2) %in% singleneg ~ amtE-.01,
.default = amtE
)
然而,这远远不是理想的,因为对于这一特定的6人组,有40个求和错误的例子.也许一些模除法是合适的,但本周五下午,我无法理解是否可以将其应用于这种情况.
任何帮助或提示都将不胜感激.