损失结转与dplyr和突变
我正在研究R中的一个税务模型,我需要进行亏损结转,我正在为如何在没有亏损结转的情况下实现这一点而奋斗!循环我的代码。也许你有个建议 可复制的示例如下:损失结转与dplyr和突变,r,dplyr,purrr,mutate,R,Dplyr,Purrr,Mutate,我正在研究R中的一个税务模型,我需要进行亏损结转,我正在为如何在没有亏损结转的情况下实现这一点而奋斗!循环我的代码。也许你有个建议 可复制的示例如下: taxable_income<-c(-10,-10,-10,-10,-10,20,20,20,20,20) #define taxable income amounts data_test<-data.frame(taxable_income) #put into data frame data_test$carry_fwd<-
taxable_income<-c(-10,-10,-10,-10,-10,20,20,20,20,20) #define taxable income amounts
data_test<-data.frame(taxable_income) #put into data frame
data_test$carry_fwd<-0 #initialize carry forward and tax payable columns
data_test$tax_payable<-0
tax_rate<-0.27 #tax rate of 27%
#what I would like to be able to do is conditionally carry-forward a loss so that I end up with the following:
data_test$carry_fwd[1]<-ifelse(data_test$taxable_income[1]<0,data_test$taxable_income[1],0) #first year, carry-forward balance only depends on in-year taxable income
data_test$tax_payable[1]<-max(data_test$taxable_income[1],0)*tax_rate #first year, taxable only depends on in-year taxable income
for(i in seq(2,NROW(data_test))) {
#carry forward any further losses and/or any carried forward losses not yet offset by income
data_test$carry_fwd[i]<-ifelse(data_test$taxable_income[i]+data_test$carry_fwd[i-1]<0,data_test$taxable_income[i]+data_test$carry_fwd[i-1],0)
#pay taxes if the income net carried forward losses is positive
data_test$tax_payable[i]<-max(data_test$taxable_income[i]+data_test$carry_fwd[i-1],0)*tax_rate
}
循环工作得很好,但是由于这是一个代码块,将被多次复制,我想找到一种方法通过更快的dplyr来实现这一点?剧本模型代码的其余部分是使用tidyverse完成的-这可能是应用purr的地方吗 以下是dplyr解决方案:
library(tidyverse)
tax_rate <- 0.27
data_test <- tibble(taxable_income = c(-10,-10,-10,-10,-10,20,20,20,20,20))
data_test %>%
mutate(cum_sum = cumsum(taxable_income),
carry_fwd = if_else(cum_sum <= 0, cum_sum, 0),
tax_payable = case_when(cum_sum > taxable_income & cum_sum > 0 ~ taxable_income * tax_rate,
cum_sum <= taxable_income & cum_sum > 0 ~ cum_sum * tax_rate,
T ~ 0)) %>%
select(-cum_sum)
结果
看起来结转fwd可以通过IFELSECUMSUMTANDABLE_收入<0,CUMSUMTANDABLE_收入,0使用baseR获得,但没有循环。是的,@AntoniosK,在某种程度上-当我进入后面的行时,我认为问题出现了,当时我只能使用结转损失的一部分来抵消当年的应税收入。AFAIK,当第i行的计算依赖于第i-1行时,除了for循环之外,不可能执行任何操作。purrr::map基本上是Lappy的tidyverse版本。@Phil为什么不在这种情况下使用滞后值?@AndrewLeach如果您想计算一些必须只考虑年内信息的指标,您可以从dplyr中按年对_进行分组。谢谢@Phil!尽管我讨厌支持专栏,但这次还是有意义的;谢谢,菲尔!我想测试这个,确保我理解它。非常感谢。这是@Charlicito的answer@Charlicito你的方法复制了结果,但我做了一些测试,它遇到了另一个问题,如果你有一段时间的利润,那么更多的亏损需要结转,因为累积金额将反映历史利润,然而,税收规则不是路径依赖的——当你在亏损之前有利润时,你不会得到不同的待遇,而仅仅是亏损。如果你用tibbleu income=c-10,-10,-10,-103000,-10,-10,-10,20,20运行你的解,你就会明白我的意思。我想我可能会被@antoniosK指出的循环所困扰。@AndrewLeach我明白你的意思了。毕竟,使用循环可能更容易:
# A tibble: 10 x 3
taxable_income carry_fwd tax_payable
<dbl> <dbl> <dbl>
1 -10 -10 0
2 -10 -20 0
3 -10 -30 0
4 -10 -40 0
5 -10 -50 0
6 20 -30 0
7 20 -10 0
8 20 0 2.7
9 20 0 5.4
10 20 0 5.4