我写了一个for循环,根据可变收入计算应付所得税。从下面的函数中,我需要一个值,但当前返回多个值。正确的答案是返回的值,但是我在编写函数时遇到麻烦,因此它只能返回该值。
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))
功能:
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)
}
}
}
我的结果
> 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
答案 0 :(得分:1)
不确定原因,但基于预期的输出和尝试,我猜您需要
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
我们首先反转数据帧,在第5列的值大于等于income
时找到第一个匹配项,然后对该行进行计算。
或者不反转数据框就可以做到
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