Search code examples
rstatisticsregressionbayesianstan

Problems adjusting Linear Regression at Stan


I'm having trouble adjusting a linear regression model on the stan. When observing the error message, the identification in the block part of the transformed parameters is noted.

See below the structure of the code in stan.

Packages:

library(rstan)
library(bayesplot)

Data:

head(Orange)
cols <- c(colnames(Orange[-1]))
Orange <- Orange[,cols]
str(Orange)

Code in stan:

See that the block structure within the stan follows the recommended pattern, however I am not able to identify which part of the code may seem wrong to me.

y = Orange$circumference
x = Orange$age
n = length(y)

regresstan = '
data{
  int n;
  real y[n];
  real x[n];
}

parameters{
  real alpha;
  real beta;
  real sigma;
}

transformed parameters{
    real mu[n];
    mu = alpha + beta*x;
}

model{
  //Priors
  alpha ~ normal(0, 100);
  beta ~ normal(0, 100);
  sigma ~ uniform(0, 100);

  //Likelihood
    y ~ normal(mu, sigma);
}
'

Error:

SYNTAX ERROR, MESSAGE(S) FROM PARSER:
No matches for: 

  real * real[ ]

Available argument signatures for operator*:

  real * real
  vector * real
  row_vector * real
  matrix * real
  row_vector * vector
  vector * row_vector
  matrix * vector
  row_vector * matrix
  matrix * matrix
  real * vector
  real * row_vector
  real * matrix

No matches for: 

  real + ill-formed

Available argument signatures for operator+:

  int + int
  real + real
  vector + vector
  row_vector + row_vector
  matrix + matrix
  vector + real
  row_vector + real
  matrix + real
  real + vector
  real + row_vector
  real + matrix
  +int
  +real
  +vector
  +row_vector
  +matrix

Expression is ill formed.
 error in 'modele28054257a16_a9d23411185fa271b60f20be43062e80' at line 16, column 23
  -------------------------------------------------
    14: transformed parameters{
    15:     real mu[n];
    16:     mu = alpha + beta*x;
                              ^
    17: }
  -------------------------------------------------

Error in stanc(file = file, model_code = model_code, model_name = model_name,  : 
  failed to parse Stan model 'a9d23411185fa271b60f20be43062e80' due to the above error.

Solution

  • The error comes from the transformed parameters block at the line

    mu = alpha + beta*x;
    

    The error is saying you can't multiply a real scalar by a real vector (the error of real * real[ ]). You can solve this by looping over the values of mu

    transformed parameters {
      real mu[n];
      for(i in 1:n) {
        mu[i] = alpha + beta * x[i];
      }
    }
    

    which resolves the issue as now you have a real scalar times a real scalar.