R:退出调用函数
在R中,是否有方法退出调用函数并返回值?类似于R:退出调用函数,r,R,在R中,是否有方法退出调用函数并返回值?类似于return(),但来自父函数 parent <- function(){ child() # stuff afterward should not be executed } child <- function(){ returnFromParent("a message returned by parent()") } parent对于父函数,列出测试列表。然后循环测试,并在第一次失败的测试时返回消息。第一次失败后,
return()
,但来自父函数
parent <- function(){
child()
# stuff afterward should not be executed
}
child <- function(){
returnFromParent("a message returned by parent()")
}
parent对于父函数,列出测试列表。然后循环测试,并在第一次失败的测试时返回消息。第一次失败后,将不会执行后续测试
示例代码:
test1 <- function(){criteria <- T; return(ifelse(criteria,T,F))}
test2 <- function(){criteria <- F; return(ifelse(criteria,T,F))}
test3 <- function(){criteria <- T; return(ifelse(criteria,T,F))}
parent <- function() {
tests <- c('test1', 'test2', 'test3')
for (i in 1:length(tests)) {
passed <- do.call(tests[i],args = list())
#print(passed)
if (!passed){
return(paste("Testing failed on test ", i, ".", sep=''))
}
}
return('Congrats! All tests passed!')
}
parent()
test1免责声明:这听起来是一个XY问题,将停止消息打印到stdout几乎没有价值,如果是交互式的,则不应该是一个问题,如果在脚本中只使用通常的重定向2>&1
将stderr消息写入stdout,或者可能使用接收器
,如中所述
现在,如果我正确理解了您的意图,我将执行以下操作以避免过多的代码重构
首先定义一个函数来处理错误:
my_stop <- function() {
e <- geterrmessage()
print(e)
}
现在让我们测试一下:
f1 <- function() {
f2()
print("This should not be seen")
}
f2 <- function() {
stop("This is a child error message")
}
明白了。我想我在找这样的东西:
parent <- function(){
parent_killing_child()
print("do not run this")
}
parent_killing_child <- function(){
do.call(return, list("my message"), envir = sys.frame(-1))
}
parent()
parent您可以让子对象返回包含状态标志的结构。只有一个状态,父级将继续。在不同的状态下,家长退出,我不认为这是个好主意。它可能使父函数对子函数的调用在逻辑上不透明。这就像一个隐藏的goto语句@G5W的想法似乎很有希望,而且更符合逻辑。更新了问题以解决我为什么要这样做。再次,在G5W的建议下:在每次调用child()
之后,您将编写类似if(attr(ans,“status”)=“fail”)return()的内容?是的,这会起作用,但是一遍又一遍地写这个似乎很尴尬。“我想做的是为stop()编写一个小的替换,它返回相同的消息“-stop
不返回任何东西。澄清你的意思。这很好。。我认为,如果您将子函数实现为do.call(return,list(“my message”),envir=as.environment(sys.frames()[[1]])
,您可以在调用堆栈的任何深度使用它。如果有人遇到与我相同的挑战,并使用源代码(“parent\u killing\u child.R”)
,那么使用envir=sys.frame(1)
会有所帮助,…还有第二个注意事项,如果在第n个父函数上并且n
可能是动态的,则可以使用:do.call(return,list(“我的消息”),envir=sys.frame(1-sys.nframe())
> f1()
[1] "Error in f2() : This is a child error message\n"
parent <- function(){
parent_killing_child()
print("do not run this")
}
parent_killing_child <- function(){
do.call(return, list("my message"), envir = sys.frame(-1))
}
parent()