使用R计算边际税率

Tom*_*hon 12 r

根据澳大利亚的边际税率,我正在编写一个函数,根据收入水平计算欠税.

我写了一个函数的简单版本,使用以下内容产生正确的税额:

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)
}
Run Code Online (Sandbox Code Playgroud)

这种方法的问题在于我已经将每个括号中的费率和支付金额硬编码到逻辑中.这使得功能变得脆弱,并且意味着我无法测试不同的速率或括号(这是我的最终目标).

我想做的是从税率表中生成逻辑.

这是我想用伪代码编写的算法作为注释的版本.

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)
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,在数据编码时,我无法概念化或编码如何产生欠税额和边际费率.

Jos*_*ien 10

这是一个可以解决问题的单线程:

income_tax <- 
function(income,
         brackets = c(18200, 37000, 80000, 180000, Inf),
         rates = c(0, .19, .325, .37, .45)) {        
    sum(diff(c(0, pmin(income, brackets))) * rates)
}
Run Code Online (Sandbox Code Playgroud)

也许最简单的方法来看看它是如何/为什么它的工作原理是用一些更简单的参数来解决核心逻辑,如下所示:

brackets <- c(1:5, Inf)

diff(c(0, pmin(.35, brackets)))
## [1] 0.35 0.00 0.00 0.00 0.00 0.00
diff(c(0, pmin(3.9, brackets)))
## [1] 1.0 1.0 1.0 0.9 0.0 0.0
diff(c(0, pmin(99, brackets)))
## [1]  1  1  1  1  1 94
Run Code Online (Sandbox Code Playgroud)

  • 我把它给了这个,因为它是最简单的,它也教会了我关于 pmin 和 diff 两个函数。其他答案也有效,但这是最优雅的。 (2认同)