我正试着聪明地写一个"stopcat“函数,它本质上是stop的简写( sprintf( "a string thing %d",val ))
下面是一小段无法工作的代码片段
library( tidyverse ) # For !!
stopcat = function( str, ... ) {
msg = sprintf( str, ... )
eval( expr( stop( !!msg ) ), parent.frame(1) )
}
pig = function() {
cat( "piggy\n" )
stopcat( "no way! %d", 6 )
24 * 44
}
pig()
它会打印出来
Error in eval(expr(stop(!!msg)), parent.frame(1)) : no way! 6
但我想
Error in pig : no way! 6
有什么想法吗?
我找到了相关的帖子How to get the name of the calling function inside the called routine?,但那里的细节似乎不适用于停止(或者我不能理解说了什么,也许)
发布于 2019-03-20 04:26:49
我不认为您可以通过这样操作计算上下文来愚弄stop
。如果确实需要识别该函数,可以尝试获取函数名称并将其添加到错误消息中,然后关闭默认表达式标签。例如
stopcat <- function( str, ... ) {
msg <- sprintf( str, ... )
fun <- deparse(sys.call(1)[[1]])
msg <- paste0("(in ", fun, "): ", msg)
stop( msg, call.=FALSE)
}
pig <- function() {
cat( "piggy\n" )
stopcat( "no way! %d", 6 )
24 * 44
}
pig()
# piggy
# Error: (in pig): no way! 6
https://stackoverflow.com/questions/55249143
复制相似问题