To part 16.3b STAN

From Wiki1

Jump to: navigation, search

Stan Code:


# Declare our data types (J is number of distinct children in our model)
# Vectorize our data, where N is the total number of observations we have

data {
  int<lower=0> N; 
  int<lower=1,upper=J> child[N];
  vector[N] x;
  vector[N] y;
  vector[N] u1;
  vector[N] u2;
} 

# Declare the data types of our parameters, where sigma_a and sigma_y are 
# Uniform(0,100) random variables

parameters {
  vector[J] b;
  vector[3] beta;
  real mu_b;
  real mu_beta;
  real<lower=0,upper=100> sigma;
  real<lower=0,upper=100> sigma_b;
  real<lower=0,upper=100> sigma_beta;
} 


transformed parameters {
  vector[J] y_hat;

  for (i in 1:N)
    y_hat[i] <- b[child[i]] + beta[1] * time[i] + beta[2] * baseage[i] + beta[3] * treatment[i];
}


model {
  b ~ normal(0, sigma_b);
  mu_b ~ normal(0, 1);
  
  mu_beta ~ normal (0,1);
  beta ~ normal (100 * mu_beta, sigma_beta);

  y ~ normal(y_hat, sigma);
}


From R, call up the the package rstan using library(rstan). Copy and paste the code above into a variable. Create a list with your data. The syntax for running the model is:

fit<- stan(model_code = code_above, data = your_data, iter= 1000, chains = 4)

Personal tools