为什么R一直说它找不到我的功能?

时间:2017-12-20 02:48:46

标签: r

我只是在学习R,而问题在于创建一个能够计算收入税额的函数。前5万税率为10%,其余税率为20%。这是我创建的功能,但无论何时我尝试调用它,我都会收到错误:'找不到功能" tax_calc"'。

    tax_calc<- function(income){
       if (income <= 50000){
          return (income*(0.10))
       } else {
          return ((50000*.1)+((income - 50000)*.2)
       }
    }

我不明白我做错了什么。谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

因为该功能无效。你试图创造它吗?

>    tax_calc<- function(income){
+        if (income <= 50000){
+           return (income*(0.10))
+        } else {
+           return ((50000*.1)+((income - 50000)*.2)
+        }
Error: unexpected '}' in:
"          return ((50000*.1)+((income - 50000)*.2)
       }"
>     }
Error: unexpected '}' in "    }"
> 

应该是:

tax_calc<- function(income){
    if (income <= 50000){
       return (income*(0.10))
    } else {
      return ((50000*.1)+(income - 50000)*.2)
   }
}

现在:

tax_calc(100000)
#[1] 15000

答案 1 :(得分:0)

您在第5行末尾添加了一个括号。尝试运行此功能:

tax_calc<- function(income){
   if (income <= 50000){
      return (income*(0.10))
   } else {
      return ((50000*.1)+((income - 50000)*.2)) # Here I added the parenthesis
   }
}

请记住,要调用函数,您可以运行代码行或在另一个脚本中使用函数。对于后者,您可以将tax_calc函数保存在脚本中,例如&#34; TaxCalc_Script.R&#34;管他呢。然后,当您需要使用该功能时,您可以使用以下内容:

source("TaxCalc_Script.R") # if the R script is in your working directory 
# or
source("C:/User.../WorkingDirectory/TaxCalc_Script.R") ## if the script is in a different folder

在后一种方式中,您可以在一个脚本中保存多个功能。当您使用source()时,脚本中的所有函数都将被调用到您的环境中。