# Access saved stan object- extract parameter number

**URL:** <https://discourse.mc-stan.org/t/access-saved-stan-object-extract-parameter-number/29035>\
**Category:** RStan\
**Tags:** rstan\
**Created:** [October 5, 2022, 4:22pm UTC](https://discourse.mc-stan.org/t/access-saved-stan-object-extract-parameter-number/29035 "2022-10-05T16:22:41Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![zhez67373](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/zhez67373/32/17433_2.png) [@zhez67373](https://discourse.mc-stan.org/u/zhez67373)\
**Post date:** [October 5, 2022, 4:22pm UTC](https://discourse.mc-stan.org/t/access-saved-stan-object-extract-parameter-number/29035/1 "2022-10-05T16:22:41Z")

</div>

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

```nohighlight
modelcode <- "
data{
  int<lower=0> N; // number of data points
  real Y[N]; // 
}

parameters{
  real mu;
  real<lower=0> eta;
}

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

model{
  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(
N=50,
Y=rnorm(50,0,1)
)

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

get_num_upars(fit)     
# number of parameters are returned as expected, in this case:2

```

- Problem

The stan object can be saved in multiple ways:

```nohighlight
# 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
saveRDS(fit,"fit.rds")
fit1 <- readRDS("fit.rds") # create a new stan object "fit1" from saved RDS file

# get_num_upars does not work with either
get_num_upars(fit1)
# 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](https://cran.r-project.org/web/packages/rstan/vignettes/stanfit-objects.html). These actions can be normally performed with the saved object fit1 without any problems.
