Calculate marginal tax rates using R

后端 未结 3 1325
闹比i
闹比i 2021-02-07 16:26

I\'m writing a function to calculate tax owed given a level of income according to Australia\'s marginal tax rates.

I\'ve written a simple version of the function that r

相关标签:
3条回答
  • 2021-02-07 17:12

    I slightly changed your brackets and rates parameters. You can solve this problem using a while loop.

    income_tax <- function(income,
        brackets = c(18200,37001,80000,180000),
        rates = c(.19,.325,.37,.45))
    {
      nbrackets <- length(brackets)  
      if(income<=brackets[1]) 
        return(0)
    
      i <- 2
      cumtax <- 0
      while(i <= nbrackets) {
        if(income > brackets[i-1] && income < brackets[i]) 
          return(cumtax + rates[i-1]*(income-brackets[i-1]))
        else 
          cumtax <- cumtax + rates[i-1]*(brackets[i]-brackets[i-1])
          i <- i + 1
      }
      # income > brackets[nbrackets]
      cumtax + rates[nbrackets] * (income - brackets[nbrackets]) 
    }
    
    incomes <- seq(0,200000,25000)
    round(sapply(incomes,income_tax),0)
    # [1]     0  1292  7797 15922 24947 34197 43447 52697 63547
    
    0 讨论(0)
  • 2021-02-07 17:19

    I think you're looking for findInterval:

    income_tax <- function(income, 
                           brackets = c(0, 18200, 37000, 80000, 180000, 180000),
                           rates = c(0, .19, .325, .37, .45)) {
      bracketInd <- findInterval(income, brackets, all.inside = TRUE)
      plus <- if (bracketInd <= 2) 0 else 
        sum(sapply(bracketInd:3, function(ind) {
          (brackets[ind] - brackets[ind - 1]) * rates[ind - 1] 
        }))
      if (length(plus) == 0) plus <- 0
      tax <- plus + (income - brackets[bracketInd]) * rates[bracketInd]
      return(tax)
    }
    

    You just find between each elements your income is, and use that as an index for brackets and the rates. I also added the values as parameters with default values.

    0 讨论(0)
  • 2021-02-07 17:24

    Here's a one-liner that does the trick:

    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)
    }
    

    Perhaps the easiest way to see how/why it works is to play around with the core bit of logic with some simpler parameters, like this:

    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
    
    0 讨论(0)
提交回复
热议问题