跳过R中for循环中的包'rstan'触发的错误
正如标题中所述,我想跳过R中for循环中rstan触发的错误,让循环继续运行。我知道也有类似的答案建议tryCatch或try,例如。但是,当错误源于循环中的stan时,它们不起作用。下面是一个简单的例子:跳过R中for循环中的包'rstan'触发的错误,r,for-loop,error-handling,stan,R,For Loop,Error Handling,Stan,正如标题中所述,我想跳过R中for循环中rstan触发的错误,让循环继续运行。我知道也有类似的答案建议tryCatch或try,例如。但是,当错误源于循环中的stan时,它们不起作用。下面是一个简单的例子: library(rstan) stancode = 'data { int<lower=0> J; // number of schools real y[J]; // estimated treatment effects
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){})
}
答案不应该修复负值,而是跳过for循环中的stan错误。谢谢大家! 我的系统在运行stan代码时遇到问题,但您是否安全地或可能地尝试了PURRS
这个答案对你有帮助吗?如果是,请将其标记为社区已意识到这一点。否则,请指出缺少的内容。谢谢
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