【问题标题】:How to fix "multi-argument returns are not permitted" when making function制作函数时如何解决“不允许多参数返回”
【发布时间】:2020-01-11 07:50:03
【问题描述】:

为了学习如何创建函数,我正在尝试制作一个计算平均值的函数,其中包含三种不同的错误代码。但是,在运行此代码时,我收到了两条不同的错误消息。

如果我尝试avg(5),它只有一个数字,我会得到“缺少参数“no”,没有默认值”。在尝试avg("f") 时,对于不是数字的东西,我得到错误:“不允许多参数返回” . 我想要的是它说明如果只给出一个数字,它需要几个数字,如果给出一个字符,参数必须是数字。我确实相信第二个问题可以通过某种“停止”命令来解决,但是我的(可能是可怕的)谷歌搜索并没有让我遇到这样的事情。 感谢所有帮助,并提前致谢!

avg <- function(x){
  ifelse(class(x) == "numeric" & length(x)>1,
         return(sum(x)/length(x)),
         ifelse(class(x)!= "numeric",
                return("Need to be numeric",
                       ifelse(length(x) <= 1,
                              return("Need more than one number"),
                              return("Unknown error")))))

  }

【问题讨论】:

    标签: r function if-statement return


    【解决方案1】:

    这只是为了向您表明问题在于您对ifelse 的不当使用。仅当您的条件长度 > 1 时才应使用它。否则,您应该(在这种特定情况下必须)使用 ifelse

    avg <- function(x){
      if (class(x) == "numeric" & length(x)>1)
             return(sum(x)/length(x)) else 
               if (class(x)!= "numeric")
                    return("Need to be numeric") else 
                      if (length(x) <= 1)
                                  return("Need more than one number") else
                                  return("Unknown error")
    
    }
    
    avg(5)
    #[1] "Need more than one number"
    avg("f")
    #[1] "Need to be numeric"
    avg(c(1.5, 1.6))
    #[1] 1.55
    

    这里还有其他问题:

    您不应返回这些消息。相反,您应该创建一个错误(使用stop)。

    您应该使用is.numeric(x) 而不是class(x) == "numeric"。对于整数,前者将为TRUE,后者不会。

    如果returnstop 如果条件为TRUE,则实际上不需要else

    【讨论】:

      【解决方案2】:

      使用您的代码而不进行简化以使其按原样工作:

      avg <- function(x){
        ifelse(
          class(x) == "numeric" & length(x)>1,
          return(sum(x)/length(x)),
          ifelse(
            class(x)!= "numeric",
            return("Need to be numeric"),
            ifelse(length(x) <= 1,
              return("Need more than one number"),
              return("Unknown error")
            )
          )
        )
      }
      
      avg(numeric())
      avg(1)
      avg(c(1, 2))
      avg("f")
      avg(c(NA, 1))
      

      请查看@Roland 的回答以提高代码质量。

      【讨论】:

      • 只有换行符,就是一模一样的代码。抱歉,我没有解释。
      猜你喜欢
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多