我有以下資料框:
x income
1 46200
2 89345
3 189982
4 255465
5 301189
6 18100
7 55234
8 900672
9 108221
10 22201
我試圖根據每個值的范圍(例如 0-20k、20-50k、50-90k、90-140k 和 >140k)對每個值應用不同的函式。這個函式看起來像:
平均稅率 = ((前邊際稅率 ((收入 - 當前區間下限)*邊際稅率))/收入
我曾嘗試使用帶有 if & else if 條件的 for 回圈,但是我在將其應用于我的 df 時收效甚微,我不確定在執行所需操作時我的替代方案是什么。我也不確定哪種 R 函式最適合這種操作。非常感謝任何幫助,因為 R 對我來說是新的。
編輯
稅表和之前的應稅金額
可重現的例子:
收入 = 60,000
Avgtax = ((6000 ((60000 - 50000)*0.35))/60000
平均稅 = 15.83%
uj5u.com熱心網友回復:
這是更友好的可重復格式的資料,最后一行添加了特定示例
dd <- read.table(text="
x income
1 46200
2 89345
3 189982
4 255465
5 301189
6 18100
7 55234
8 900672
9 108221
10 22201
11 60000", header=T)
首先,將您的稅務資料從影像中移到表格中
taxinfo <- read.table(text="
min max rate prior
0 20000 0 0
20000 50000 .2 0
50000 90000 .35 6000
90000 140000 .4 20000
140000 Inf .5 40000", header=TRUE)
現在我們可以使用每個括號的行索引更輕松地從該表中提取相關資訊。我們可以使用以下方法輕松找到每個人的支架cut()
dd$bracket <- cut(dd$income, breaks=c(-Inf, taxinfo$max),labels = FALSE)
我們使用表中的最大值taxinfo來創建中斷。我們將此值分配給表中的新列。現在我們知道了這個人所在的每個括號的索引。我們可以使用該資訊來索引taxinfo表來進行計算
dd$avgtax <- with(taxinfo,
(prior[dd$bracket] (dd$income-min[dd$bracket])*rate[dd$bracket]) / dd$income
)
和prior的值來自taxinfo。我們使用括號值來索引每個組的值的列。我們也將其分配給新的資料列。這是輸出minrate
x income bracket avgtax
1 1 46200 2 0.11341991
2 2 89345 3 0.22128547
3 3 189982 5 0.34209030
4 4 255465 5 0.38256708
5 5 301189 5 0.40039477
6 6 18100 1 0.00000000
7 7 55234 3 0.14179491
8 8 900672 5 0.46669154
9 9 108221 4 0.25215439
10 10 22201 2 0.01982794
11 11 60000 3 0.15833333
uj5u.com熱心網友回復:
這對于包來說相對簡單dplyr。首先,這里有一些我們可以使用的示例資料作為示例:
df <- data.frame(
x = c(1, 2, 3, 4, 5, 6),
income = c(46200, 89345, 189982, 255465, 301189, 60000)
)
df
輸出:
x income
1 1 46200
2 2 89345
3 3 189982
4 4 255465
5 5 301189
6 6 60000
現在,我們可以推匯出我們需要的其他值并執行最終計算:
library(dplyr)
df %>%
mutate(
marginal_rate = case_when(
income < 20000 ~ 0,
income >= 20000 & income < 50000 ~ .2,
income >= 50000 & income < 90000 ~ .35,
income >= 90000 & income < 140000 ~ .4,
income >= 140000 ~ .5
),
prior_taxable_amount = case_when(
income < 50000 ~ 0,
income >= 50000 & income < 90000 ~ 6000,
income >= 90000 & income < 140000 ~ 20000,
income >= 140000 ~ 40000
),
current_bracket_lower_bound = case_when(
income < 20000 ~ 0,
income >= 20000 & income < 50000 ~ 20000,
income >= 50000 & income < 90000 ~ 50000,
income >= 90000 & income < 140000 ~ 90000,
income >= 140000 ~ 140000
),
avgtax =
(prior_taxable_amount
((income - current_bracket_lower_bound) *
marginal_rate)) / income
)
輸出:
x income marginal_rate prior_taxable_amount current_bracket_lower_bound avgtax
1 1 46200 0.20 0 20000 0.1134199
2 2 89345 0.35 6000 50000 0.2212855
3 3 189982 0.50 40000 140000 0.3420903
4 4 255465 0.50 40000 140000 0.3825671
5 5 301189 0.50 40000 140000 0.4003948
6 6 60000 0.35 6000 50000 0.1583333
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/444580.html
下一篇:我如何訂購線是正確的?
