这是代码:
setGeneric("ifLet",
function(sym, x, body1, body2, ...) {
standardGeneric("ifLet")
})
#' @name ifLet
#' @export
setMethod("ifLet",
signature(sym = "name", x = "ANY", body1 = "ANY", body2 = "ANY"),
function(sym, x, body1, body2 = {}) {
e = new.env()
sym_str = deparse(substitute(sym))
ifLet(sym_str, x, body1, body2)
})
#' @rdname ifLet
#' @export
setMethod("ifLet",
signature(sym = "character", x = "ANY", body1 = "ANY", body2 = "ANY"),
function(sym, x, body1, body2 = {}) {
stopifnot(length(sym) == 1)
e = new.env()
e[[sym]] = x
if(e[[sym]]) {
eval(substitute(body1), e)
} else {
eval(substitute(body2), e)
}
})
# test
ifLet("myvar", 3 > 2, {
as.integer(myvar) * 3
}, {
as.integer(myvar) + 1
}) == 3
测试在 reple 中通过,但在 testthat 上下文中失败,为什么?
这是错误消息:
1. Error: ifLet ----------------------------------------------------------------
object 'myvar' not found
1: withCallingHandlers(eval(code, new_test_environment), error = capture_calls)
2: eval(code, new_test_environment)
3: eval(expr, envir, enclos)
4: ifLet("myvar", 3 > 2, {
as.integer(myvar) * 3
}, {
as.integer(myvar) + 1
}) at test.bedinfo.R:60
5: ifLet("myvar", 3 > 2, {
as.integer(myvar) * 3
}, {
as.integer(myvar) + 1
}) at /Users/kaiyin/EclipseWorkspace/CollapsABEL/R/0_ifLen.R:58
6: .local(sym, x, body1, body2, ...)
7: eval(substitute(body1), e) at /Users/kaiyin/EclipseWorkspace/CollapsABEL/R/0_ifLen.R:80
8: eval(expr, envir, enclos)
9: .handleSimpleError(function (e)
{
e$calls <- head(sys.calls()[-seq_len(frame + 7)], -2)
signalCondition(e)
}, "object 'myvar' not found", quote(eval(expr, envir, enclos))) at test.bedinfo.R:61