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
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.