我使用以下代码使用R.计算税金,其中两个变量可以作为参数给出。使用数据集时,我想根据类别计算税额。我是包装开发的新手。请帮助我解决这个问题。
当我插入数据集时,仅计算第一类并收到此Waring消息时出现错误。
警告消息:如果if(category == 1){:条件的长度> 1,则仅使用第一个元素
IIT<- function(income,category) {
if (category == 1){
if (income > 0 && income <= 18200) {
tax <- 0
} else if (income > 18200 && income <= 37000) {
tax <- (income - 18200) * .10
} else if (income > 37000 && income <= 80000) {
tax <- 3572 + (income - 37000) * .20
} else if (income > 80000 && income <= 180000) {
tax <- 17547 + (income - 80000) * .30
} else if (income > 180000 && Inf) {
tax <- 54547 + (income - 180000) * .40
}
return(tax)}
else if (category==2){
if (income > 0 && income <= 18200) {
tax <- 0
} else if (income > 18200 && income <= 37000) {
tax <- (income - 18200) * .15
} else if (income > 37000 && income <= 80000) {
tax <- 3572 + (income - 37000) * .25
} else if (income > 80000 && income <= 180000) {
tax <- 17547 + (income - 80000) * .35
} else if (income > 180000 && Inf) {
tax <- 54547 + (income - 180000) * .45
}
return(tax)
}
}
首先,尝试使事情保持简单。您的语法比实际需要的要复杂。对于一对值,您可以将函数改写为:
single.IIT <- function(income, category) {
if (income < 0) stop("Error in IIT: income must bei > 0.")
if (category == 1){
if (income <= 18200) return(0)
if (income <= 37000) return((income - 18200) * .19)
if (income <= 80000) return(3572 + (income - 37000) * .325)
if (income <= 180000) return(17547 + (income - 80000) * .37)
return(54547 + (income - 180000) * .45)
}
if (category==2){
if (income <= 18200) return(0)
if (income <= 37000) return((income - 18200) * .15)
if (income <= 80000) return(3572 + (income - 37000) * .25)
if (income <= 180000) return(17547 + (income - 80000) * .35)
return(54547 + (income - 180000) * .45)
}
stop("ERROR in IIT: category must be either 1 or 2.")
}
在简短版本中,您可以更轻松地发现错误。由于您想一次处理多个数据,因此需要向量化:
IIT <- Vectorize(single.IIT)
现在您可以对其进行测试:
> IIT( income = c(23000, 500000, 0), category = c(1, 2, 1))
[1] 912 198547 0
> IIT( income = c(0, 0, 500, 500, 19000, 19000, 40000, 40000),
+ category = c(1, 2, 1, 2, 1, 2, 1, 2))
[1] 0 0 0 0 152 120 4547 4322
> IIT( income = c(0, 18000, -20), category = c( 1, 1, 1))
Error in (function (income, category) :
Error in IIT: income must bei > 0.
> IIT( income = c(0, 18000, 202), category = c( 1, 1, 5))
Error in (function (income, category) :
ERROR in IIT: category must be either 1 or 2.
编辑:在注释中,您询问了如何将其与数据框一起使用:
expl <- data.frame(income = c(30000, 40000, 50000,60000),
bodyweight = c(75, 60, 45, 98),
nationality = c("F", "CH", "D", "AU"),
category = c(1, 2, 1, 2))
# we need the first and the fourth column in that dataframe
expl$tax <- IIT(expl[[1]], expl[[4]])
print(expl)
plot(tax ~ income, data = expl, col=category, pch=19)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句