我有一个用例,其中需要根据一些代码生成的警告数量进行一些控制:
# clear all warnings
assign("last.warning", NULL, envir = baseenv())
for (i in 0:100) {
# call warning-generating code here
x <- warnings()
cat(paste('There were',length(x),'warnings generated\n'))
if (length(x)>10) {
# do something
}
# clear all warnings again
assign("last.warning", NULL, envir = baseenv())
}
由于某种原因,此代码无法正常工作。该代码将始终给出There were 0 warnings generated
...为什么?如果我在循环外运行有问题的警告生成代码,则会生成非零数量的警告...
答案 0 :(得分:1)
不确定这是否是您的目标吗?
# clear all warnings
assign("last.warning", NULL, envir = baseenv())
x <- rep(NA, 100)
for (i in 1:100) {
# call warning-generating code here
x[i] <- warning()
cat(paste('There were',sum(!is.na(x)),'warnings generated\n'))
if (sum(!is.na(x))>10) {
# do something
}
# clear all warnings again
assign("last.warning", NULL, envir = baseenv()
}
看起来像错字-afaik warnings()只会向您显示警告-在循环中此品脱位置仍然为NULL; warning()将生成。