gpt4 book ai didi

r - 在R的for循环中跳过由 `rstan`软件包触发的错误

转载 作者:行者123 更新时间:2023-12-03 08:18:54 24 4
gpt4 key购买 nike

如标题所述,我想跳过R中for循环中rstan触发的错误,并让循环继续运行。我知道也有类似的建议tryCatch()try()的答案,例如this。但是,当错误源自循环内的stan时,它们将不起作用。这是一个最小的示例:

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代码时遇到了麻烦,但是您尝试了purrr还是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

关于r - 在R的for循环中跳过由 `rstan`软件包触发的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62015861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com