if语句+;在R停车

if语句+;在R停车,r,function,if-statement,R,Function,If Statement,背景: 在一个名为GG的R函数中,我有两个元素(请参见下面的R代码),type和width。type元素只能接受以下字符参数:“normal”或“cauchy”。当类型为“cauchy”时,宽度可以是任意数字,也可以是以下三个字之一:“中等”、“宽”或“非常宽”。但是,当类型为“正常”时,宽只能是一个数字 问题: 首先,当我运行GG(type=“normal”,width=“medium”)时,函数应该停止并返回一条消息,但是我遇到了一个错误,我如何修复它 第二,这些if语句能否更有效地编写 G

背景:

在一个名为GG的R函数中,我有两个元素(请参见下面的R代码),typewidthtype元素只能接受以下字符参数:“normal”或“cauchy”。当
类型
为“cauchy”时,
宽度可以是任意数字,也可以是以下三个字之一:“中等”、“”或“非常宽”。但是,当
类型
为“正常”时,
只能是一个数字

问题:

首先,当我运行
GG(type=“normal”,width=“medium”)
时,函数应该停止并返回一条消息,但是我遇到了一个错误,我如何修复它

第二,这些if语句能否更有效地编写

GG = function(type, width){


width <- if(type == "cauchy" & width == "wide") { sqrt(2)/2 } else

if(type == "cauchy" & width == "medium") { 1/2 } else 
  if(type == "cauchy" & width == "very wide") { 1 } else 
    if(type == "normal" & is.character(width) ) {
      stop(message(cat("You must provide a number")))
    } else { width }

return(width)

}

GG(type = "normal", width = "medium") ## if you I run this, I get an error.
GG=函数(类型、宽度){

宽度根据定义,停止是一条错误消息

停止执行当前表达式并执行错误操作

因此,这是一个错误并不奇怪,但它正在做您想要做的事情,即停止并返回消息

42的建议可能有以下含义:

GG2 <- function(type, width) {

  width_vals <- list(
    "wide" = sqrt(2)/2,
    "medium" = 1/2,
    "very wide" = 1
  )

  if (type == "normal" & is.character(width)) {
    stop("You must provide a number")
  } else if (type == "cauchy") {
      width <- width_vals[[width]]
  }
  return(width)
}


GG2(type = "normal", width = 2) # 2
GG2(type = "normal", width = "wide") # error
GG2(type = "cauchy", width = "wide") # 0.7071068
GG2(type = "cauchy", width = "medium") # 0.5
GG2(type = "cauchy", width = "very wide") # 1

GG2根据定义,stop是一条错误消息

停止执行当前表达式并执行错误操作

因此,这是一个错误并不奇怪,但它正在做您想要做的事情,即停止并返回消息

42的建议可能有以下含义:

GG2 <- function(type, width) {

  width_vals <- list(
    "wide" = sqrt(2)/2,
    "medium" = 1/2,
    "very wide" = 1
  )

  if (type == "normal" & is.character(width)) {
    stop("You must provide a number")
  } else if (type == "cauchy") {
      width <- width_vals[[width]]
  }
  return(width)
}


GG2(type = "normal", width = 2) # 2
GG2(type = "normal", width = "wide") # error
GG2(type = "cauchy", width = "wide") # 0.7071068
GG2(type = "cauchy", width = "medium") # 0.5
GG2(type = "cauchy", width = "very wide") # 1

GG2为GG创建一个列表参数。函数的一个参数然后提取命名项。@42-,您是否可以提供一个答案?请使用
stop(“您必须提供一个数字”)
the
stop()
函数会触发一个错误。这就是它的工作原理。不确定您到底期望的是什么。您到底得到了什么错误?为GG创建一个列表。为函数创建一个参数,然后提取命名项。@42-,您是否可以提供一个答案?另外,请使用
停止(“您必须提供一个数字”)
停止()
函数会触发一个错误。这就是它的工作原理。不确定您到底期望的是什么。您到底得到了什么错误?