Problem with linear regression model on StataStan


#1

Hi there,

I am getting an error when trying to implement the simple linear regression model from the reference manual. The initial bernoulli example from the example do-file works fine. However, when I try to modify that example and build it into a linear regression model, something starts going wrong. I have tried to take a step by step approach, and the problem pops up as soon as I add a third line with a third variable in the data.

Here is the error I am getting:

variable does not exist; processing stage=data initialization; variable name=x; base type=int

Warning: non-fatal error reading metadata
Error: error reading header
libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: Error with header of

input file in parse
#############################################

Output from optimizing to find mode

#############################################

/bin/bash: ~/cmdstan//mystanmodel: No such file or directory
unexpected end of file
r(612);

And the code that generates the error:
//create the data
clear
set obs 10
gen y=0
replace y=1 in 2
replace y=1 in 10
gen x=0
replace x=1 in 2
count
global N=r(N)

// write the model from Stata into a plain text file



global cmdstandir "~/cmdstan/"
cd “~/cmdstan/”

tempname writemodel
file open writemodel' using "mystanmodel.stan", write replace #delimit ; foreach line in "data { " " int<lower=0> N; " " int<lower=0,upper=1> x[N];" " int<lower=0,upper=1> y[N];" "} " "parameters {" "real alpha;" "real beta;" " real<lower=0> sigma;" "} " "model {" " for (n in 1:N) " " y[n] ~ normal(alpha + beta*x[n], sigma);" "}" {; #delimit cr file writewritemodel’ "line'" _n } file closewritemodel’

// call Stan
stan y, modelfile(“mystanmodel.stan”) cmd("$cmdstandir") globals(“N”) load mode

And finally, the working Bernoulli example:

clear
set obs 10
gen y=0
replace y=1 in 2
replace y=1 in 10
count
global N=r(N)

// write the model from Stata into a plain text file



global cmdstandir "~/cmdstan/"
cd “~/cmdstan/”

tempname writemodel
file open writemodel' using "mystanmodel.stan", write replace #delimit ; foreach line in "data { " " int<lower=0> N; " " int<lower=0,upper=1> y[N];" "} " "parameters {" " real<lower=0,upper=1> theta;" "} " "model {" " theta ~ beta(1,1);" " for (n in 1:N) " " y[n] ~ bernoulli(theta);" "}" {; #delimit cr file writewritemodel’ "line'" _n } file closewritemodel’

// call Stan
stan y, modelfile(“mystanmodel.stan”) cmd("$cmdstandir") globals(“N”) load mode



What is going on here? Is there something obvious that I am missing?

Ferdinand


#2

OK, classical beginner’s mistake, I found the solution now. Stata simply did not send the newly created variable to the data file. To solve this, I modified the command line to:

stan y x, modelfile(“mystanmodel.stan”) cmd("$cmdstandir") globals(“N”) load mode


#3

Thanks for reporting back with the solution.