I am trying to program (in Rstan) a regression with time-varying intercept and constant slope. After the first time-step (data point) the intercept may undergo a random walk. Here are the files: file TestRW1.stan:

data {

int<lower=1>N;

real S[N];

real R[N];

}

transformed data{

real<lower=0>hlogamn;//mean of the normal prior on log alpha

real<lower=0>hlogasd;//std dev of the normal prior on log alpha

hlogamn=1.5078;

hlogasd=0.3486;

}

parameters {

real logalpha[N];

real walk[N]; //annual random walk error ~N(0, sigmaw).

real<lower=1000, upper=30000>beta; //population-specific slope (capacity) parameters

real<lower=0, upper=2.0>sigmaw; //standard error of the annual random walk

real<lower=0,upper = 2.0>sigma; //population-specific process error of the weight-length relationship.

}

model {

logalpha[1]~normal(hlogamn, hlogasd) T[-4.60, 2.89];

log(R[1]/S[1]) ~ normal(logalpha[1] - S[1]/beta, sigma);

for (i in 2:N) {

walk[i]~normal(0,sigmaw);

logalpha[i] = logalpha[i-1]+walk[i];

log(R[i]/S[i]) ~ normal(logalpha[i] - S[i]/beta, sigma);

}

}

file: TestRW1.R:

Skagit <- read.table(“TestRWdata1.txt”, header = TRUE)

N<-nrow(Skagit)

S<-Skagit$Spawners

R <-Skagit$Recruits

stanDat<- list(“S”,“R”, “N”)

fit<-stan(file = ‘TestRW1.stan’, data = stanDat, iter = 100, chains = 1)

traceplot(fit,“sigma”)

print(fit)

When I run “fit…” I receive the following error message:

SYNTAX ERROR, MESSAGE(S) FROM PARSER:

## attempt to assign variable in wrong block. left-hand-side variable origin=parameter

error in ‘model15346f4f170c_TestRW1’ at line 25, column 25

```
23: for (i in 2:N) {
24: walk[i]~normal(0,sigmaw);
25: logalpha[i] = logalpha[i-1]+walk[i];
^
26: log(R[i]/S[i]) ~ normal(logalpha[i] - S[i]/beta, sigma);
```

PARSER EXPECTED:

Error in stanc(file = file, model_code = model_code, model_name = model_name, :

failed to parse Stan model ‘TestRW1’ due to the above error.

In addition: Warning message:

In readLines(file, warn = TRUE) :

incomplete final line found on 'C:\Stan\Stock_Recruit\Tests\TestRW1.stan’

Data set:

#Test spawner and recruit

#data for BYs 1 to 12

"Spawners" "Recruits"

7448 7107

7870 5038

3780 6073

4584 5529

5394 5154

6818 2429

7332 3702

6382 2494

6757 6174

4242 6093

4887 5814

2502 8627

The idea is pretty simple. After the initial time-step (where the intercept parameter ‘logalpha’ is drawn from a normal random distribution, the values of logalpha in each subsequent timestep is expected to be equal to logalpha(t-1) plus a normal random (‘walk’) that has a zero mean. So, it seems that after calculating the posterior (for log(R(t)/S(t)), logalpha needs to be updated for the next time-step by adding w(t) to logalpha(t-1). It would seem that this must be done in the model block. But the error indicates that this is illegal???

What is the correct way to program this? What am I failing to understand.