简体   繁体   English

跳过由 R 中的 for 循环中的 package `rstan` 触发的错误

[英]skip errors triggered by the package `rstan` in a for loop in R

As stated in the title, I wanted to skip errors triggered by rstan in a for loop in R and let the loop continue running.如标题所述,我想在rstan的 for 循环中跳过 rstan 触发的错误,让循环继续运行。 I know there are similar answers suggesting tryCatch() or try() , such as this .我知道有类似的答案建议tryCatch()try() ,例如this However, they do not work when the error originates from stan within a loop.但是,当错误源自循环中的stan时,它们不起作用。 Here is a minimal example:这是一个最小的例子:

library(rstan)

stancode = 'data {
  int<lower=0> J;          // number of schools
  real y[J];               // estimated treatment effects
  real<lower=0> sigma[J];  // s.e. of effect estimates
}
parameters {
  real mu;
  real<lower=0> tau;
  vector[J] eta;
}
transformed parameters {
  vector[J] theta;
  theta = mu + tau * eta;
}
model {
  target += normal_lpdf(eta | 0, 1);
  target += normal_lpdf(y | theta, sigma);
}'

schools_data <- list(
  J = 8,
  y = c(28,  8, -3,  7, -1,  1, 18, 12),
  sigma = c(-15, 10, 16, 11,  9, 11, 10, 18)#Intentionally created a negative value here
)

for (i in 1:3) {
  tryCatch({fit1 <- stan(model_code  = stancode, data = schools_data,
               chains = 1, iter = 1000, refresh = 0)}, error=function(e){})
}

The answer is not supposed to fix the negative value, but skipping the stan error in a for loop.答案不应该修复负值,而是在 for 循环中跳过 stan 错误。 Thank you!谢谢!

My system has troubles to run the stan code but did you try purrr s safely() or possibly() ?我的系统在运行 stan 代码时遇到了麻烦,但是您是否尝试purrr s safe safely()或 possible possibly()

x <- list(1, "d", 3)
purrr::map(x, ~1/.x)
# error in 1/.x: non numeric argument for binary operator
purrr::map(x, safely(~1/.x))
# [[1]]
# [[1]]$result
# [1] 1
#  
# [[1]]$error
# NULL
#  
#  
# [[2]]
# [[2]]$result
# NULL
#  
# [[2]]$error
# <simpleError in 1/.x: non numeric argument for binary operator>
#   
#   
# [[3]]
# [[3]]$result
# [1] 0.3333333
#  
# [[3]]$error
# NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM