# findRowErrors.R 

## DEBUG:  Identify which row is causing an error in an *apply

TODO:  Compare this against findErrorRows_OLD.R
       (such as supress warnings, etc)


############################
findErrors <- findRowErrors <-function(theData, fun, margin=1, retErrorInfo=FALSE)  {

  #TODO:  Add (...)  to fun.   or Maybe expression?

  # if theData is multi-dimensional, use apply
  if(!is.null(dim(theData))) {
    theErrors <- 
    apply(theData, margin, function(x){
      err <- try(fun(x), silent=TRUE)
      if(class(err)=="try-error"){
        return(attr(err, "condition"))
      }
      return (NA)
    })  

  # else theData is single-dimension, use sapply
  }  else  {
    theErrors <- 
    sapply(theData, simplify=T, FUN=function(x){
      err <- try(fun(x), silent=TRUE)
      if(class(err)=="try-error"){
        return(attr(err, "condition"))
      }
      return (NA)
    })  
    names(theErrors) <- (1:length(theErrors))
  }


  ## RETURN: 

  # if flag is true, return the actual error information
  if (retErrorInfo)
    return (theErrors[!is.na(theErrors)])

  # else return just the row(or vector) indexes or names
  n <- names((theErrors[!is.na(theErrors)]))
  if (sum(is.na(as.numeric(n))) == 0 )
    return(as.numeric(n))
  return(n)

}

##############################
