3

I want to extract z in the trasformed data block from the stanfit object f. Is it possible?

    library(rstan)


 m <- stan_model(model_code = '
                            data{real x;}
                            transformed data{real z; z = chi_square_rng(x); }
                            parameters {real y;} 
                            model {y ~ normal(z,1);}')
 f <- sampling(m, data=list(x=1), iter = 100)
Camford Oxbridge
  • 834
  • 8
  • 21
  • 1
    No, it's not currently possible (other than as saving it as a generated quantity as @MDEWITT suggests below). Also, we strongly recommend writing Stan programs in their own files so that you can use transpose and quotes in them and so that you can interpret line numbers in errors. – Bob Carpenter Sep 16 '19 at 12:53

1 Answers1

3

I would add a new value into generated quantities like this:

library(rstan)
m <- stan_model(model_code = '
                            data{real x;}
                            transformed data{real z; z = chi_square_rng(x); }
                            parameters {real y;} 
                            model {y ~ normal(z,1);}
                            generated quantities {real zhat = z;}')
f <- sampling(m, data=list(x=1), iter = 100)

This returns valid values

print(f, pars = "zhat")

     mean se_mean sd 2.5%  25%  50%  75% 97.5% n_eff Rhat
zhat 0.16       0  0 0.16 0.16 0.16 0.16  0.16     2 0.98

And you can extract the values, just to show a few of the results:

> extract(f)[["zhat"]]
  [1] 0.16445 0.16445 0.16445 0.16445 0.16445 0.16445
  [7] 0.16445 0.16445 0.16445 0.16445 0.16445 0.16445
 [13] 0.16445 0.16445 0.16445 0.16445 0.16445 0.16445
MDEWITT
  • 2,338
  • 2
  • 12
  • 23