R 在参数默认值中使用If语句
我想知道在参数的默认值中使用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
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")
}