Skip to content

Instantly share code, notes, and snippets.

@khakieconomics
Created September 23, 2018 14:52
Show Gist options
  • Save khakieconomics/7369f45951954f7bd761be236c4e1ac1 to your computer and use it in GitHub Desktop.
Save khakieconomics/7369f45951954f7bd761be236c4e1ac1 to your computer and use it in GitHub Desktop.
Censored time and group random effects normal linear model.
data {
int N; // number of observations
int T; // number of time periods
int I; // number of groups
int P; // number of controls
int<lower = 1, upper = T> time[N]; // time index
int<lower = 1, upper = I> group[N]; // group index
vector[N] Y;
matrix[N, P] X; // you should include group/time means in X
}
parameters {
real alpha; // intercept
real<lower = 0> sigma; // scale
vector[P] beta; // slopes
vector[T] z_t; // time effects
vector[I] z_i; // group effects
real<lower = 0> scale_zt; // the scale of the time effects
real<lower = 0> scale_zi; // the scale of the group effects
}
model {
// priors (make sure data is appropriately scaled)
// note this notation is just shorthand for "update the log posterior by normal(alpha | 0, 1)", for example.
// we've
alpha ~ normal(0, 1);
beta ~ normal(0, 1);
sigma ~ inv_gamma(1, 1);
scale_zt ~ inv_gamma(1, 1);
scale_zi ~ inv_gamma(1, 1);
// we'll use a non-centered parameterization of the random effects
z_t ~ normal(0, 1);
z_i ~ normal(0, 1);
// Likelihood
for(i in 1:N) {
if(Y[i] <= 0.0) {
// censored case.
target += normal_lcdf(0.0 | alpha + z_t[time[i]] * scale_zt + z_i[group[i]] * scale_zi + X[i]*beta, sigma);
} else {
// non-truncated case
target += normal_lpdf(Y[i] | alpha + z_t[time[i]] * scale_zt + z_i[group[i]] * scale_zi + X[i]*beta, sigma);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment