пропустить ошибки, вызванные пакетом `rstan` в a для l oop в R - PullRequest
0 голосов
/ 26 мая 2020

Как указано в заголовке, я хотел пропустить ошибки, вызванные rstan в a для l oop в R, и позволить l oop продолжить работу. Я знаю, что есть похожие ответы, предлагающие tryCatch() или try(), например, это . Однако они не работают, если ошибка возникает из stan в al oop. Вот минимальный пример:

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

Предполагается, что ответ не исправляет отрицательное значение, а пропускает стандартную ошибку в a для l oop. Спасибо!

1 Ответ

1 голос
/ 26 мая 2020

У моей системы проблемы с запуском стандартного кода, но вы пробовали purrr s safely() или 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
...