I have been trying to figure out how to include a function f of X in a regression model Y ~ f(X) with Stan (specifically through R) and I think I found something that works (in the sense that it doesn’t fail :))
In this case, the adstock function is a transformation of X with a single parameter called ‘rate’ below. Is placing this in “transformed parameters” the proper place within the Stan program?
data {
int<lower=0> N; // number of observations
real x[N]; // x
real Y[N]; // outcome
}
parameters {
real<lower=0.0> b0; // intercept
real b1; // slope on x
real<lower=0.0> sigma; // sd of error
real <lower=0.0, upper=1.0> rate; //adstock rate
}
transformed parameters {
matrix[N, 1] adstock_x; //hold new adstock x
real mu[N]; // linear predictor
//adstock transformation
adstock_x[1,1]=x[1];
for (i in 2:N)
{
adstock_x[i,1]=x[i]+rate*adstock_x[i-1,1];
}
//linear predictor
for (n in 1:N) {
mu[n] = b0+b1*adstock_x[n,1];
}
}
model {
//likelihood
Y ~ normal(mu, sigma);
// priors
b0 ~ normal(1500,500);
b1 ~ normal(0,30);
sigma ~normal(1500,1000);
rate ~ uniform(0,1);
}