【问题标题】:Function returning unwanted multiple values返回不需要的多个值的函数
【发布时间】:2023-03-25 02:56:01
【问题描述】:

问题

我编写了一个 for 循环来根据可变收入计算应付所得税。从下面的函数中,我需要一个值,但它当前返回多个。正确答案在返回的值中,但我在编写函数以使其仅返回该值时遇到问题。

我的尝试

数据:
df1 <- structure(list(`Taxable income` = c("$18,201 – $37,000", "$37,001 – $87,000", 
"$87,001 – $180,000", "$180,001 and over"), `Tax on this income` = c("19c for each $1 over $18200", 
"$3572 plus 32.5c for each $1 over $37000", "$19822 plus 37c for each $1 over $87000", 
"$54232 plus 45c for each $1 over $180000"), cumm_tax_amt = c(0, 
3572, 19822, 54232), tax_rate = c(19, 32.5, 37, 45), threshold = c(18200, 
37000, 87000, 180000)), class = "data.frame", row.names = c(NA, 
-4L))
功能:
tax_calc <- function(data, income) {

  #loop starts at the highest tax bracket first
  for (i in nrow(data):1) {

  #if statement checks if income above the thresholds in col 5
    if(income >= data[i,5]) {

      #the marginal income is calc'ed (i.e. $180,001 - $180,000) and multiplied by the marginal rate (i.e. $1 x 0.45)
      print(((income - data[i,5]) * (data[i,4]/100)) + data[i,3])

      #if income is not above any thresholds in col 5 then return zero
    } else {
      print(0)
    }
  }
}
我的结果
> tax_calc(df1, 18201)
[1] 0
[1] 0
[1] 0
[1] 0.19

> tax_calc(df1, 50000)
[1] 0
[1] 0
[1] 7797
[1] 6042

> tax_calc(df1, 180001)
[1] 54232.45
[1] 54232.37
[1] 50047.33
[1] 30742.19

成功的样子

>tax_calc(data = df1, 18201)
0.19

>tax_calc(data = df1, 50000)
7797

>tax_calc(data = df1, 180001)
54232.45

【问题讨论】:

  • 删除 else 语句应该修复第一个。但如果你只想要 1 个响应,为什么要运行一个循环?
  • 一般你应该有函数return一个结果,而不仅仅是print它。

标签: r for-loop purrr


【解决方案1】:

不完全确定原因,但基于预期的输出和尝试,我猜你需要

tax_calc <- function(data, income) {
   rev_data <- data[rev(seq_len(nrow(df1))), ]
   i <- which.max(income >= rev_data[, 5])
  ((income - rev_data[i,5]) * (rev_data[i,4]/100)) + rev_data[i,3]
}

tax_calc(df1, 18201)
#[1] 0.19 
tax_calc(df1, 50000)
#[1] 7797
tax_calc(df1, 180001)
#[1] 54232.45

我们首先反转数据帧,当第 5 列的值大于等于income 时找到第一个匹配项,并对该行执行计算。

或者不反转我们可以做的数据帧

tax_calc <- function(data, income) {
   i <-tail(which(income >= data[, 5]), 1)
   if (length(i) > 0) 
     return(((income - data[i,5]) * (data[i,4]/100)) + data[i,3])
   else
     return(0)
}

tax_calc(df1, 18199)
#[1] 0
tax_calc(df1, 18201)
#[1] 0.19

【讨论】:

  • 对低于 18199 的收入值使用帖子中的最后一个公式,该函数返回 numeric(0) 而不是 0。有没有简单的方法来解决这个问题?
  • @Dom 是的,我们可以检查是否在i 中找到任何索引。更新了答案。
猜你喜欢
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
  • 2019-08-03
  • 2011-05-05
  • 2010-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多