R语言mcp包中set.seed函数失效问题求助:变点分析结果每次运行不一致
Hey Laura, I’ve run into this exact issue with mcp and JAGS before—let’s break down why your results are still varying even with set.seed(42) and how to fix it!
The problem boils down to this: R’s base set.seed() doesn’t control the random number generator (RNG) used by JAGS, which is the underlying engine mcp relies on for Bayesian sampling. Your set.seed(42) only affects base R functions, not the MCMC chains running inside JAGS.
Fix 1: Use mcp’s Built-in seed Parameter
The easiest way to lock in reproducibility is to use the seed argument directly in the mcp() function. This parameter handles both R-level and JAGS-level RNG seeds, so you get consistent results every time. Update your code like this:
library(rjags) library(mcp) # Define your model (unchanged) model = list(y~1+x,~0+x,~0+x,~0+x,~0+x,~0+x) # Keep base R seed for extra safety, but the key is the seed in mcp() set.seed(42) fit_mcp = mcp(model, data=hosp_df, seed = 42) # Add this seed argument! # Rest of your workflow (unchanged) summary(fit_mcp) plot(fit_mcp) newdata = data.frame(x = c(2023:2040)) prediction <- fitted(fit_mcp, newdata = newdata)
Fix 2: Explicitly Set the JAGS Seed (For Extra Robustness)
If you still see any variability (unlikely, but possible with older mcp versions), you can pass a JAGS-specific seed through the control argument. This directly tells JAGS to use your specified seed for its MCMC chains:
fit_mcp = mcp( model, data=hosp_df, seed = 42, control = list(jags.seed = 42) # Explicitly set JAGS seed here )
How to Verify It’s Working
Run the modified code twice in a row and compare the summary(fit_mcp) output—posterior means, credible intervals, and even the chain diagnostics should be identical. Your plot(fit_mcp) and predictions should also match perfectly across runs.
内容的提问来源于stack exchange,提问作者Laura Lim

