尝试捕获for循环以进行回归

时间:2020-07-18 11:45:00

标签: r error-handling try-catch regression

我正在通过这段代码进行很多回归

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

print(vif(lmtest))引发一些错误:there are aliased coefficients in the model

如果遇到这些错误,我想运行alias(lmtest)

即使有关于trycatch()的一些话题,我也无法解决。解决这个问题的最简单方法是什么?

1 个答案:

答案 0 :(得分:1)

R中的

tryCatch可以在Python中很好地处理错误。您可以尝试使用tryCatch来捕获错误并根据需要重新运行代码。请注意,您可以检查命令是否返回了错误,甚至准确地返回了什么错误。

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

您可以通过使用类似

的内容来捕获特定错误
if (bad$message == "Random error encountered") {
  print("adapting workflow")
}