0

I am running a lot of regressions through this code

vek <- read_excel("h24.xlsx")
filterfile <- read_excel("filterfile.xlsx")

x <- c(filterfile$Column)
sink("D:/test.csv")
for (temp_var in x){
  h24 <- filter(vek,KEY == temp_var)
  h24 <- na.omit(h24)
  frml <- UNITS ~ h36+ z24+ z36+ pr
  
  if (length(unique(h24$`F`)) > 1) frml <- update.formula(frml, ~ F + .)
  if (length(unique(h24$`D`)) > 1) frml <- update.formula(frml, ~ D + .)
  
  lmtest <- lm(frml, data = h24)
  
  
print(vif(lmtest))
}
sink()

The print(vif(lmtest)) throws some errors: there are aliased coefficients in the model

In case of these erros, I would like to run alias(lmtest)

Even though there are a few threads about trycatch() I could not fix it. What would be the easiest way to solve this?

M.m.mm
  • 27
  • 1
  • 5
  • Please share a reproducible example, so we can help you better. It's hard to code if you can't see the problem. See also: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Julian_Hn Jul 18 '20 at 11:55

1 Answers1

1

tryCatch in R can look up to nice error handling in Python. You can try using tryCatch to catch the error and rerunning your code as necessary. Note that you can inspect if command returned an error and even what error exactly.

throwRandomError <- function(x = 0.5) {
  if (runif(1) > x) {
    stop("Random error encountered")
  } else {
    return(x)
  }
}

set.seed(2)
ok <- tryCatch(
  throwRandomError(x = 0.5),
  error = function(e) e
)

bad <- tryCatch(
  throwRandomError(x = 0.5),
  error = function(e) e
)

str(bad)

List of 2
 $ message: chr "Random error encountered"
 $ call   : language throwRandomError(x = 0.5)
 - attr(*, "class")= chr [1:3] "simpleError" "error" "condition"

# Catch any type of class, error, simpleError or condition.
# Only one is probably enough, but left here for redundancy.
if (class(bad) %in% c("error", "simpleError", "condition")) {
  print("Rerunning lmtest")
  result <- print(alias(lmtest))
}

You could catch specific error by using something along the lines of

if (bad$message == "Random error encountered") {
  print("adapting workflow")
}
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197