【问题标题】:How to identify the warning generated instances of an operation in a loop?如何识别循环中操作的警告生成实例?
【发布时间】:2015-06-12 09:02:26
【问题描述】:

基于这个solution,我制定了下面的代码来为33个变量执行chisq.test

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

此代码产生 9 个警告,可能是由于违反了为 chisq.test 所做的假设。我想确定针对哪些i 实例发出了警告?

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

【问题讨论】:

  • 尝试将print(i) 放入函数中。我不确定警告是在循环之后还是在每次迭代时打印的。但你可以试试

标签: r debugging warnings sapply chi-squared


【解决方案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)
})

带有options(warn=1) 的警告在发生时会打印出来。 (来自Andrie answerprint(i) 告诉我它是在哪个迭代中产生的。

【讨论】:

  • 感谢您提供最简单的答案。我想知道是否有任何方法可以在出现警告时仅打印 i 值。因为我只有 33 次迭代,所以检查起来没什么大不了的。当有大量迭代时,比如 1000+,知道发出 i 的警告将是一项整洁的任务。
  • 我会努力找出来的
  • 是的,我找到的所有解决方案都与tryCatch 函数有关。我觉得罗兰的回答比较合适
【解决方案2】:

您可以使用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!

【讨论】:

  • 感谢您提供相当避孕的答案。我会理解它并用于我的要求。
猜你喜欢
  • 1970-01-01
  • 2020-09-12
  • 1970-01-01
  • 1970-01-01
  • 2017-12-23
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多