如何在循环中识别警告生成的操作实例?

时间:2015-06-12 09:02:26

标签: r debugging warnings sapply chi-squared

根据此solution,我制定了以下代码,为33个变量执行chisq.test

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

此代码产生9个警告,希望是因为违反了对chisq.test的假设。我想确定哪些i警告发布的实例?

我认为初学者不需要这个简单问题的可重复的例子。

2 个答案:

答案 0 :(得分:1)

我生成此示例以重现问题:

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)
})
发生{p}时会发出options(warn=1)警告。 (来自Andrie answerprint(i)告诉我它产生的迭代次数。

答案 1 :(得分:0)

您可以使用tryCatch并在匿名函数中返回警告消息以及chisq.test中的list结果。

示例:

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!