Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在参数默认值中使用If语句_R - Fatal编程技术网

R 在参数默认值中使用If语句

R 在参数默认值中使用If语句,r,R,我想知道在参数的默认值中使用if语句是否合法 例如: foo <- function(x, description=if(x>0) "pos" else "non-pos") { cat(x, description, "\n") } 但是,当以交互方式调试它时,我在多次尝试访问description参数时会出现“promise ready under evaluation”(承诺已在评估中)错误: > debug(foo) > foo(1) debugging i

我想知道在参数的默认值中使用if语句是否合法

例如:

foo <- function(x, description=if(x>0) "pos" else "non-pos") {
  cat(x, description, "\n")
}
但是,当以交互方式调试它时,我在多次尝试访问
description
参数时会出现“promise ready under evaluation”(承诺已在评估中)错误:

> debug(foo)
> foo(1)
debugging in: foo(1)
debug at #1: {
    cat(x, description, "\n")
}
Browse[2]> description
debug at #1: [1] "pos"
Browse[3]> description
Error: promise already under evaluation: recursive default argument reference or earlier problems?

谢谢

注意提示:
第一次浏览[2]
,第二次浏览[3]。所发生的情况是,您正在单步执行设置
说明
默认值的表达式,即
如果(x>0)“pos”或“non pos”
,但尚未返回。打印时

debug at #1: [1] "pos"
它不是打印
description
的值,而是打印即将执行的语句

如果您点击return(或
n
转到下一个语句),您将得到
浏览[2]
再次提示,一切正常:

> foo(1)
debugging in: foo(1)
debug at #1: {
    cat(x, description, "\n")
}
Browse[2]> description
debug at #1: [1] "pos"
Browse[3]> 
[1] "pos"
Browse[2]> description
[1] "pos"
Browse[2]> 
将函数更改为

foo <- function(x, description={if(x>0) v <- "pos" else v <-"non-pos"; v}) {
  cat(x, description, "\n")
}

foo 0)v这是绝对允许的-主要包中的许多函数在默认参数中使用if语句。但不知道为什么会导致这样的错误!通常,如果试图将x=x作为参数,则会出现错误。
foo <- function(x, description={if(x>0) v <- "pos" else v <-"non-pos"; v}) {
  cat(x, description, "\n")
}