我正在尝试计算每个家庭的税后收入,数据框架如下:
id hhinc
1 1 53880
2 2 49501
3 3 37525
4 4 28791
5 5 91049
6 6 133000
7 7 12299
8 8 23000
9 9 58100
10 10 9764 其中hhinc是家庭收入。
然后,我创建了以下函数来计算每个家庭缴纳的税款:
taxpaid = function(hhinc) {
if (hhinc > 0 & hhinc <= 19999) {tax = 0}
else if (hhinc > 20000 & hhinc <= 49999) {tax = (hhinc - 20000)*.15}
else if (hhinc > 50000 & hhinc <= 199999) {tax = 4499.85 + ((hhinc - 50000)*.25)}
else if (hhinc > 200000 & hhinc <= 999999) {tax <- 37499.75 + ((hhinc - 200000)*.39)}
else if (hhinc > 1000000) {tax <- 311999.61 + ((hhinc - 1000000)*.85)}
return(tax)
}由于此函数仅适用于标量输入,因此我将该函数向量化:
taxpaid_vec = Vectorize(taxpaid, vectorize.args = "hhinc")但是,当我使用这个函数来计算已支付的税款时,我得到的是非数字输出。因此,我不能从每个家庭的收入中减去所支付的税款,以确定税后收入。我想知道如何修复我的代码,以便获得纳税的数字输出。
发布于 2019-12-20 12:51:34
将if/else替换为ifelse,以使您的函数向量化。
taxpaid = function(hhinc) {
ifelse(hhinc > 0 & hhinc <= 19999, 0,
ifelse(hhinc > 20000 & hhinc <= 49999, (hhinc - 20000)*.15,
ifelse(hhinc > 50000 & hhinc <= 199999, 4499.85 + ((hhinc - 50000)*.25),
ifelse(hhinc > 200000 & hhinc <= 999999, 37499.75 + ((hhinc - 200000)*.39),
ifelse(hhinc > 1000000, 311999.61 + ((hhinc - 1000000)*.85), NA)))))
}应用函数
df$tax_income <- taxpaid(df$hhinc)
df
# id hhinc tax_income
#1 1 53880 5469.85
#2 2 49501 4425.15
#3 3 37525 2628.75
#4 4 28791 1318.65
#5 5 91049 14762.10
#6 6 133000 25249.85
#7 7 12299 0.00
#8 8 23000 450.00
#9 9 58100 6524.85
#10 10 9764 0.00您还可以查看?dplyr::case_when来处理此类嵌套条件。
https://stackoverflow.com/questions/59419786
复制相似问题