You can use try()
(or the more elaborate tryCatch()
to do this. For example,
x = 1
simple <- function(p,q){
q <- try(force(q), silent = TRUE)
if (inherits(q, "try-error")) {
warning("No data")
q <- NULL
}
return(q)
}
test = simple(x,y)
#> Warning in simple(x, y): No data
Created on 2021-01-28 by the reprex package (v0.3.0)
What the force()
function does is evaluate the argument. If that fails, it returns an error: but try()
catches that. (You don't actually need to call force(q)
, it would be enough to use try(q)
, but I think the explicit version is clearer.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…