Pergunta

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

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() 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).

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 returns the following message:

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

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

Foi útil?

Solução 2

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)
}

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

sum(is.na(out))

Outras dicas

Here's a function that sometimes fails

f <- function() {
    r <- rnorm(1)
    if (r > 1)
        stop("oops")
    r
}

we allocate a result vector and set up a counter to update the ith element

out <- numeric(100)
i <- 0

then repeatedly try to call the function. If there's an error, we don't increment i or record the result, but instead go directly to the next iteration

while (i < length(out)) {
    tryCatch({
        out[[i + 1]] <- f()
        i <- i + 1
    }, error=function(...) NULL)
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top