我正在编写一个函数来根据给定的收入水平计算所欠税款澳大利亚的边际税率 https://www.ato.gov.au/rates/individual-income-tax-rates/.
我编写了该函数的一个简单版本,该函数使用以下代码得出正确的应缴税额:
income_tax <- function(income) {
# Calculate income tax liability based on income
#
# Returns the amount of income tax owed
if (income > 0 & income <= 18200) {
tax <- 0
} else if (income > 18200 & income <= 37000) {
tax <- (income - 18200) * .19
} else if (income > 37000 & income <= 80000) {
tax <- 3572 + (income - 37000) * .325
} else if (income > 80000 & income <= 180000) {
tax <- 17547 + (income - 80000) * .37
} else if (income > 180000) {
tax <- 54547 + (income - 180000) * .45
}
return(tax)
}
这种方法的问题在于,我已将每个括号中的费率和支付金额硬编码到逻辑中。这使得该功能变得脆弱,并且意味着我无法测试不同的费率或括号(这是我的最终目标)。
我想做的是从税率表生成逻辑。
这是我想用伪代码编写的算法作为注释进行的操作的一个版本。
income_tax <- function(income) {
# Calculate income tax liability based on income
#
# Returns the amount of income tax owed
brackets <- c(18200,37001,80000,180000,180000)
rates <- c(0,.19,.325,.37,.45)
tax_rates <- data.frame(brackets, rates)
for (i in 1:nrow(tax_rates)) {
# if income is in bracket_X then:
# tax <- (income - bracket_X[i-1]) * rate_X + minimum_tax_from_bracket_X[-1]
}
return(tax)
}
我的问题是,当数据像这样编码时,我无法概念化或编码如何生成所欠税款和边际税率。