Exception: variable does not exist Error in Stan

I am new and have been trying to run Stan in Rmarkdown. I have been able to run my own small bits of code, but now I am trying to run simple linear regression in rstan in an Rnotebook with the standard cars dataset.

I have the following error

is.na() applied to non-(list or vector) of type 'NULL’data with name x is not numeric and not usedis.na() applied to non-(list or vector) of type 'NULL’data with name y is not numeric and not usedError in new_CppObject_xp(fields$.module, fields$.pointer, …) :
Exception: variable does not exist; processing stage=data initialization; variable name=x; base type=vector_d (in ‘model67844d3cb5eb_stan_67845af13b64’ at line 3)

Here is all of my code

{r}
library(tidyverse)
library(rstan)

Regression

{stan, output.var=simple_regression}
data {
int<lower=0> N;
vector[N] x;
vector[N] y;
}
parameters {
real alpha;
real beta;
real<lower=0> sigma;
}
model {
y ~ normal(alpha + beta * x, sigma);
}
{r}
#Cars
data(cars)
plot(cars$speed~cars$dist)
y <- select(cars,speed) %>% as.list()
x <- select(cars,dist) %>% as.list()
N <- nrow(cars) 
N
str(x)
str(y)
class(y)
simp_lreg <- sampling(simple_regression,
                      data=list(y,x,N))
rstan::summary(simp_lreg)

Does it work with list(y=y, x=x, N=N)?

1 Like
simp_lreg <- sampling(simple_regression,
                      data=list(y=y,x=x,N=N))

gave the error

Exception: mismatch in number dimensions declared and found in context; processing stage=data initialization; variable name=x; dims declared=(50); dims found=(1,50)

This is the solution to my problem:

#Cars
data(cars)
plot(cars$speed~cars$dist)
y <- select(cars,speed) 
x <- select(cars,dist) 
N <- nrow(cars) 
N
x
str(x)
str(y)
class(y)
simp_lreg <- sampling(simple_regression,
                      data=list(y=y$speed,x=x$dist,N=N))
rstan::summary(simp_lreg)

The key was recognize that I had to refer to the column name x$dist as opposed to just x

1 Like

That’s a step in the right direction. Now you just have to pass x in as a
vector rather than a matrix/array

1 Like

Thank sakrejda, I have been to same problems. It was just that.

1 Like