我有一个类似于下面在循环内创建矩阵的函数。
foo <- function(x, y, z) {
out <- list(a1 = NULL, a2 = NULL, a3 = NULL)
for (i in 1:3) {
t <- 100 * i
a <- matrix(x, y + t, z)
out[[i]] <- t(a)
}
return(out)
}
以下运行正常。
p <-foo(NA,100,50)
但是以下给出了
cannot allocate vector of length
错误q <- foo(NA, 3500000, 50)
我想在函数中出现
message
或adjust arguments 'y' and 'z'
错误之后添加一些其他cannot allocate vector of length
,例如too many elements specified
。我正在尝试
try
和tryCatch
,但是当错误在循环内发生时,似乎无法获得所需的结果。这该怎么做?
最佳答案
您可以使用简单的装饰器模式来丰富错误消息:
safify <- function(f){
function(...){
tryCatch({
f(...)
},
error=function(e){
msg=conditionMessage(e)
if(grepl("cannot allocate", msg)){
msg=paste(msg, " Adjust arguments 'y' and 'z'", sep='.')
return(msg)
}
msg
})
}
}
safefoo = safify(foo)
#res=safefoo(NA, 3500000, 50)
#> res
#[1] "cannot allocate vector of size 667.6 Mb. Adjust arguments 'y' and 'z'"
这样,您可以捕获可能发生的每种错误,并丰富所需的错误。
关于r - 在R中出现错误消息后添加更多详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27598228/