If-then命令生成字符串作为r中的输出
我试图在如下数据框架中计算每个家庭的税后收入:If-then命令生成字符串作为r中的输出,r,if-statement,R,If Statement,我试图在如下数据框架中计算每个家庭的税后收入: 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是家庭收入 然后,我创建了以下函
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)
}
但是,当我使用此函数计算已支付的税款时,我会收到非数字输出。因此,我无法从每个家庭的收入中减去已缴纳的税款来确定税后收入。我想知道如何修复我的代码,以便获得纳税的数字输出 将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_ 将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_