本文介绍了使用tryCatch()捕获引导循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用 tryCatch()的知识不足,但是发现在进行中的讨论中很难找到一个好的解决方案.

I have insufficient knolwedge on the use of tryCatch() but have found it hard to find a good solution in the ongoing discussions.

我有一个自编程函数,该函数返回一个对象.它实际上是一个列表对象,但为简单起见,假设它是一个标量.我正在使用 for()循环来引导此函数.我的循环具有以下形式:

I have a self-programmed function which returns an object. It is actually a list object, but for simplicity assume it is a scalar. I am using a for() loop to bootstrap this function. My loop is of the following form:

boot<-1000
for(i in 1:boot){
  bootstrap_data<-data[sample(nrow(data),nrow(data),replace=T),]
  out[i]<-myfunction(bootstrap_data,X,...)
}

myfunction()有时会返回错误消息,因为它使用 lm()将模型拟合到数据的子集上,然后从其他数据中预测新数据子集.然后可能发生的情况是,对于某些因素,某些水平偶然地没有出现在用于拟合的数据中,但确实出现在预测子集中.确实很少发生这种情况(例如,大约每15,000次迭代),但是确实发生了(我需要多次引导 myfunction().)

myfunction() sometimes returns an error message, because it uses lm() to fit a model on a subset of the data and then predict new data from a different subset. Then it can happen that for certain factors some levels by chance do not appear in the data used to fit, but they do appear in the prediction subset. This does happen very rarely (say, roughly every 15,000 iterations), but it does happen (I need to bootstrap myfunction() a lot of times).

我想使用 tryCatch()或类似的函数来捕获引导循环.此外,我想定义一个索引,该索引计算 tryCatch()在整个循环中必须捕获该函数的频率.最后,无论错误发生多少次,我都希望有一个恒定的 boot .

I want to use tryCatch() or a similar function to catch my bootstrap loop. Furthermore, I would like to define an index that counts how often across the loops tryCatch() had to catch the function. Finally, I would like to have a constant number boot regardless of the number of times the error occured.

R返回以下消息:

    Error in model.frame.default(Terms,newdata,na.action=na.action,
xlev=object$xlevels) : factor X has new levels 2

X lm()中用户指定的预测变量.我不确定2代表什么,我猜是新级别的数量(?).

X is a user specified predictor in lm(). I am not sure what 2 stands for, I guess the number of new levels(?).

推荐答案

包装有时会在尝试"中引发错误的函数通常对我有用.

Wrapping the function that sometimes throws an error in a "try" usually works for me.

boot<-1000
for(i in 1:boot){
  bootstrap_data<-data[sample(nrow(data),nrow(data),replace=T),]
  out[i] = NA  #
  try({
    out[i]<-myfunction(bootstrap_data,X,...)
  }, silent=T)
}

如果您要计算抛出的错误数,可以对NA进行总结.

If you want to count the number of errors thrown you can sum up the NA's in out.

sum(is.na(out))

这篇关于使用tryCatch()捕获引导循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 17:16