在循环中删除带有警告的迭代

Drop the iteration with warning in a loop

在R中,我需要在循环中完成一个集合,但有时计算会产生警告,我想去掉任何有警告的结果,所以最终结果将没有任何有警告的元素。例如:

result <- numeric(10)
for (i in 1:length(result)){
 element <- sample(-1:1,1)
 result[i] <- log(element)
}

你可以看到什么时候element=-1log(element)=NaNNaN仍然会存储到result,而R会给出警告。我只是想根据警告避免这样NaN存储到result。这是一个简单的情况,我们可以有其他选择。但是我要面对的情况要复杂得多。所以我希望我能找到一种方法,如果发生了警告,那么我们就可以去掉警告的计算结果。

您可以尝试使用 tryCatch() 并将其与递归相结合以避免警告消息和 NaN 条目:

set.seed(222) # for reproducibility of the pseudo-random results
set_to_log <- function() {
  element <- sample(-1:2,1)
  tryCatch(log(element), warning = function(w) set_to_log())
}
result <- numeric(10)
for (i in 1:length(result)){
  result[i] <- set_to_log()
}
#> result
# [1] 0.6931472      -Inf 0.6931472 0.6931472      -Inf      -Inf 0.0000000      -Inf 0.0000000 0.6931472

这里,function(w)指定函数set_to_log()应该在出现警告的情况下再次调用,如果生成NaN结果就会发生警告。通过将 tryCatch() 与此递归一起使用,代码将不会发出任何警告,并且 vectorresult 将不包含任何 NaN 条目。然而,result 向量可能包含 -Inf 个条目,这些条目对应于 log(0) 的情况并且在没有警告的情况下生成。