R 尝试捕获用于回归的循环

R 尝试捕获用于回归的循环,r,error-handling,try-catch,regression,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

我通过这段代码运行了很多回归

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

R中的
vek
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")
}