首页 > 解决方案 > 返回不需要的多个值的函数

问题描述

问题

我编写了一个 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

标签: rfor-looppurrr

解决方案


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

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

推荐阅读