【发布时间】:2023-03-25 02:56:01
【问题描述】:
问题
我编写了一个 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
【问题讨论】:
-
删除 else 语句应该修复第一个。但如果你只想要 1 个响应,为什么要运行一个循环?
-
一般你应该有函数
return一个结果,而不仅仅是print它。