簡體   English   中英

在制作函數時如何修復“不允許多參數返回”

[英]How to fix “multi-argument returns are not permitted” when making function

要學習如何創建函數,我試圖制作一個計算平均值的函數,其中包含三個不同的錯誤代碼。 但是,運行此代碼時,我收到兩條不同的錯誤消息。

如果我嘗試avg(5) ,這只是一個數字,我得到“參數”沒有“缺少,沒有默認”。 當嘗試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")))))

  }

這只是為了向您展示問題是您對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 ,后者則不為。

如果您在條件為TRUE returnstop則實際上不需要else

使用您的代碼而不進行簡化使其按原樣運行:

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提高代碼質量的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM