I have written a for loop to calculate income tax payable based on the variable income. From the function below I need a single value but it currently returns multiple. The right answer is in the values returned but I am having trouble writing the function so that it returns just that value.
df1 <- structure(list(`Taxable income` = c("$18,201 – $37,000", "$37,001 – $87,000",
"$87,001 – $180,000", "$180,001 and over"), `Tax on this income` = c("19c for each $1 over $18200",
"$3572 plus 32.5c for each $1 over $37000", "$19822 plus 37c for each $1 over $87000",
"$54232 plus 45c for each $1 over $180000"), cumm_tax_amt = c(0,
3572, 19822, 54232), tax_rate = c(19, 32.5, 37, 45), threshold = c(18200,
37000, 87000, 180000)), class = "data.frame", row.names = c(NA,
-4L))
The function:
tax_calc <- function(data, income) {
#loop starts at the highest tax bracket first
for (i in nrow(data):1) {
#if statement checks if income above the thresholds in col 5
if(income >= data[i,5]) {
#the marginal income is calc'ed (i.e. $180,001 - $180,000) and multiplied by the marginal rate (i.e. $1 x 0.45)
print(((income - data[i,5]) * (data[i,4]/100)) + data[i,3])
#if income is not above any thresholds in col 5 then return zero
} else {
print(0)
}
}
}
My result
> tax_calc(df1, 18201)
[1] 0
[1] 0
[1] 0
[1] 0.19
> tax_calc(df1, 50000)
[1] 0
[1] 0
[1] 7797
[1] 6042
> tax_calc(df1, 180001)
[1] 54232.45
[1] 54232.37
[1] 50047.33
[1] 30742.19
>tax_calc(data = df1, 18201)
0.19
>tax_calc(data = df1, 50000)
7797
>tax_calc(data = df1, 180001)
54232.45
Not completely sure about the reason but based on expected output and attempt I guess you need
tax_calc <- function(data, income) {
rev_data <- data[rev(seq_len(nrow(df1))), ]
i <- which.max(income >= rev_data[, 5])
((income - rev_data[i,5]) * (rev_data[i,4]/100)) + rev_data[i,3]
}
tax_calc(df1, 18201)
#[1] 0.19
tax_calc(df1, 50000)
#[1] 7797
tax_calc(df1, 180001)
#[1] 54232.45
We first reverse the dataframe, find the first occurrence when the 5th column has value greater than equal to income
and perform the calculation on that row.
Or without reversing the dataframe we can do
tax_calc <- function(data, income) {
i <-tail(which(income >= data[, 5]), 1)
if (length(i) > 0)
return(((income - data[i,5]) * (data[i,4]/100)) + data[i,3])
else
return(0)
}
tax_calc(df1, 18199)
#[1] 0
tax_calc(df1, 18201)
#[1] 0.19
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments