3

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.

Community
  • 1
  • 1
Prradep
  • 5,506
  • 5
  • 43
  • 84
  • Try putting `print(i)` into a function. I am not sure if the warnings are printed after loop or on each iteration. but you can try – Andriy T. Jun 12 '15 at 09:07

2 Answers2

1

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.

Community
  • 1
  • 1
Andriy T.
  • 2,020
  • 12
  • 23
  • Thanks for the simplest possible answer. I was wondering if any way possible to only print `i` values when there is a warning. As I have only 33 iterations, it's not a big deal to check. When there are huge number of iterations, say 1000+, it will be a tidy task to know warning issuing `i`'s. – Prradep Jun 12 '15 at 10:39
  • I'll try to find it out – Andriy T. Jun 12 '15 at 13:02
  • Yeah, all the solution I have found is related with `tryCatch` function. I think Roland's answer is more appropriate – Andriy T. Jun 12 '15 at 19:59
0

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!
Roland
  • 127,288
  • 10
  • 191
  • 288