How to identify the warning generated instances of an operation in a loop?

1.2k views Asked by At

Based on this solution, I have formulated the below code to perform chisq.test for 33 variables.

sapply(Indices,function(i){
  chisq.test(data.cleaned[,i],data.cleaned$Out)$p.value })

This code produces 9 warnings, hopefully due to the violation of the assumptions made for chisq.test. I would like to identify for which instances of i the warnings are issued ?

I assume that there is no need of a reproducible example for this simple question from a beginner.

2

There are 2 answers

1
Roland On

You could use tryCatch and return warning messages from your anonymous function together with the chisq.test result in a list.

Example:

fun <- function(x) {
  if (x == 2) warning("It's a two!")
  return(x^2)
}
lapply(1:3, function(i) tryCatch(list(result = fun(i), warning = "no warning"),
                                 warning = function(w) list(result = fun(i), 
                                                            warning = as.character(w))))

#[[1]]
#[[1]]$result
#[1] 1
#
#[[1]]$warning
#[1] "no warning"
#
#
#[[2]]
#[[2]]$result
#[1] 4
#
#[[2]]$warning
#[1] "simpleWarning in fun(i): It's a two!\n"
#
#
#[[3]]
#[[3]]$result
#[1] 9
#
#[[3]]$warning
#[1] "no warning"
#
#
#Warning message:
#In fun(i) : It's a two!
3
Andriy T. On

I generate this example to reproduce the problem:

df <- data.frame(x=rep(c("a","b"), 22))

options(warn=1)

sapply(1:nrow(df), function(i){
  df[i,"x"] <- letters[round(rnorm(1,mean=2, sd = .5),0)]
  print (i)
})

with options(warn=1) warning is printed when it occurs. (from Andrie answer) And print(i) tells me on which iteration it is produced.