【问题标题】:Having trouble creating error statements when creating function创建函数时无法创建错误语句
【发布时间】:2019-09-17 06:24:57
【问题描述】:

我正在 R 中创建一个函数,用于使用公式 - F=P\left(1+\frac{i}{100t}\right)^{ty} 计算复利。

如果 P、i、t 或 y 参数中的任何一个不是数字或负数,我需要创建错误消息,如果 i 超出 0-100 范围,则需要创建错误消息。

当我尝试运行代码时,我收到错误消息: 错误:意外的“,”在: " stop("参数 'P','i','t' 和 'y' 必须是数字") 如果(P," 并且不确定如何解决它或我做错了什么。到目前为止的代码是:

compound <- function(P,i,t=12,y,plotit=FALSE,...){

   # 1. Check arguments and throw errors here using 'if' statements
  if(!is.numeric(P,i,t,y)){
    stop("Argument 'P','i','t' and 'y' must be numeric")
    if(P,i,t,y<0){
      stop("Argument 'P','i','t' and 'y' must be non-negative")
      if(i<0||i>100){
        stop("'i' must be within the range 0-100 percent")
      }
    }
  }

  if(plotit==TRUE){
    # 2. Do plot if necessary here according to 'plotit' argument
    y <- floor(y)
    f <- P*((1+(i/100*t))^t*y)
  for(i in length(y)){
    plot(f, type = 's')
   } 
  }
  else {
  final.result <- f
  # Calculate final result here
  return(final.result)
  }
}

任何关于如何改进代码的帮助都会很棒!

【问题讨论】:

  • if(!(is.numeric(P) &amp;&amp; is.numeric(i) &amp;&amp; is.numeric(t) &amp;&amp; is.numeric(y)))if(P &lt; 0 || i &lt; 0 || t &lt; 0 || y &lt; 0)

标签: r


【解决方案1】:

问题是您将四个参数传递给is.numeric(P,i,t,y)。它只能带一个。

if(!all(sapply(list(P,i,t,y), is.numeric)))

这将检查所有参数是否都是数字。

if(P,i,t,y&lt;0) 也会出现类似的问题,所以使用:

if(!all(sapply(list(P,i,t,y), function(x) x >= 0)))

此外,您已经嵌套了这些 if 语句,这意味着不会计算第二个和第三个。将它们从您的第一个 if 语句中移出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多