Access saved stan object- extract parameter number

Issue: the function get_num_upars to access the number of unconstrained parameters from a stan objecti does not work with previously saved stan object

  • Test Model and Data
modelcode <- "
  int<lower=0> N;          // number of data points
  real Y[N];               // 

  real mu;
  real<lower=0> eta;

transformed parameters{
  real<lower=0> sigma;
  sigma = 1 / eta;

  mu ~ normal(0,10);
  sigma ~ cauchy(0,1);

generated quantities{
  real Yhat[N];
  for(n in 1:N){
    Yhat[n] = Y[n] + 1;


model <- stan_model(model_code = modelcode)

dataList <- list(

fit <- sampling(object = model, data = dataList)

# number of parameters are returned as expected, in this case:2
  • Problem

The stan object can be saved in multiple ways:

# method 1: save the stan object as .rdata
save(list="fit",file = "savefile.rdata")
load("savefile.rdata")        # load stan object "fit" into global environment

# method 2: save as rds
fit1 <- readRDS("fit.rds")  # create a new stan object "fit1" from saved RDS file

# get_num_upars does not work with either
# an error is returned: the model object is not created or not valid

A list of actions are mentioned at Access contents of stanfit object. These actions can be normally performed with the saved object fit1 without any problems.