如何解决:条件的长度 > 1 且仅使用第一个元素

How to solve: the condition has length > 1 and only the first element will be used

我使用以下代码使用 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)