Changing parameter names in a 'stanfit' object

I tried the names<- replacement method to change the parameter
names of an object with class "shinystan", using sensible names (no duplicates, …). But the launch_shinystan function of the shinystan package no longer works as expected after the renaming. For instance, the DIAGNOSE page seems to ignore the parameter names and only diagnoses for the log posterior lp__.

library(rstan)
ex_model_code <- "
  data {
    int<lower=0> n;   
    matrix[n, 3] X;   // predictor matrix
    vector[n] y;      // response
  }
  parameters {
    vector[3] beta;       // coefficients 
    real<lower=0> sigma;  
  }
  model {
    y ~ normal(X * beta, sigma);  // likelihood
  }"
## some data make a "model matrix" as in 'lm'
set.seed(123)
n <- 30
X <- matrix(runif(n * 2, max = 10), ncol = 2)
colnames(X) <- c("foo", "bar")
df <- data.frame(X, y = 1 + X %*% c(1, 2) + rnorm(n, sd = 0.5))
X <- model.matrix(y ~ foo + bar, data = df)
dl <- list(n = n, X = X, y = df$y)
## fit the model 
fit <- stan(model_code = ex_model_code, data = dl, chains = 2)
library(shinystan)
my_sso <- launch_shinystan(fit)
## Change the names to standard R lm's names.  'summary' works...
names(fit)
fit2 <- fit
names(fit2) <- c(colnames(X), "sigma", "lp__")
summary(fit2)
## ... but shinystan no longer works
my_sso2 <- launch_shinystan(fit2)

1 Like

Unfortunately I don’t think this direct renaming is supported… The stanfit is quite a complex object. There is a piece of code in brms that does parameter renaming at brms/rename_pars.R at master · paul-buerkner/brms · GitHub so maybe you would be able to modify it to suit your needs? (note that in the code I linked x$fit is the stanfit object of interest).

Hope that helps at least a little!

1 Like

Thank you for your answer. I will try to adapt the code for my example. Since it is for a GEV model, I have 3 formulas and model matrices yet no random effects (for now). All in all, although I have two naming conventions in “my” model object and in its stanfit part, the names are usually easy enough to understand.