R,for循环中的警告排序

时间:2015-10-20 11:44:12

标签: r

在R中,for循环内部的函数不会按顺序打印警告。

for(i in sample(-2:2)){
  cat(sprintf("running for %d\n", i))
  j= sqrt(i)
}

#running for 0
#running for -2
#running for 1
#running for -1
#running for 2
#Warning messages:
#1: In sqrt(i) : NaNs produced
#2: In sqrt(i) : NaNs produced

警告消息最后打印,我们不清楚警告哪些值。我正在寻找警告massege序列

#running for 0

#running for -2
#Warning messages:
#1: In sqrt(i) : NaNs produced

#running for 1

#running for -1
#Warning messages:
#2: In sqrt(i) : NaNs produced

#running for 2

如何强制R以顺序方式打印警告(或在执行代码后立即打印警告)?

2 个答案:

答案 0 :(得分:4)

immediate.函数中有一个warning参数,特别是为此目的,尝试在函数中设置

if (i < 5) warning("A warning", immediate. = TRUE)

例如

foo <- function(i){
  if (i < 5) warning("A warning", immediate. = TRUE)
  i }

for (i in 3:7){
  cat(sprintf("running for %d\n", i))
  foo(i)
}

# running for 3
# Warning in foo(i) : A warning
# running for 4
# Warning in foo(i) : A warning
# running for 5
# running for 6
# running for 7

修改:根据您的新更新,您可能需要将您的功能包装到tryCatch,例如

set.seed(222)
for(i in sample(-2:2)){
   cat(sprintf("running for %d\n", i))
   tryCatch(sqrt(i), warning = function(w) message(paste(w, "\n")))
}

# running for 2
# running for -2
# simpleWarning in sqrt(i): NaNs produced
# 
# 
# running for -1
# simpleWarning in sqrt(i): NaNs produced
# 
# 
# running for 1
# running for 0

答案 1 :(得分:0)

?options开始,列出选项warn以填充此角色。这不是最好的选择;如果警告正确使用,tryCatch很可能更清晰,但它对调试很有用。

  

警告:设置警告消息的处理。如果警告是否定的全部   警告被忽略。如果warn为零(默认值)警告   存储直到顶级函数返回。如果10或更少的警告   发出信号说明他们将被打印,否则会有一条消息说明如何   许多人都发出了信号。创建了一个名为last.warning的对象,可以   通过功能警告打印。如果警告是一个,警告是   在它们出现时打印。如果警告是两个或更大,则所有警告都是   变成了错误。

options(warn=1)
for(i in sample(-2:2)){
    cat(sprintf("running for %d\n", i))
    j <- sqrt(i)
}
#running for -2
#Warning in sqrt(i) : NaNs produced
#running for 2
#running for 0
#running for 1
#running for -1
#Warning in sqrt(i) : NaNs produced

您还可以使用以下内容:

currentWarnLevel <- getOptions("warn")
# code that should print warn straight away
options(warn = currentWarnLevel)

如果您使用的是自定义记录器,我发现最好覆盖options(warning.expression)并使用withCallingHandlers,然后重置warning.expression