Camford Oxbridge
Camford Oxbridge

Reputation: 894

How to pass a logical R object to a data block in a Stan file

If a list of data includes a logical variable x, namely, x=TRUE or x=FALSE. Then how to declare such a variable in a Stan file?

For example, if an R object x is an integer, then

data{

int <lower=0>x;

}

I want to know its logical version. I guess

data{

               bool x;

    }

and it does not work as following;

SYNTAX ERROR, MESSAGE(S) FROM PARSER:
 error in 'foo' at line 16, column 0
  -------------------------------------------------
    14:   
    15: 
    16: bool x;
       ^
    17: 
  -------------------------------------------------

PARSER EXPECTED: <one of the following:
  a variable declaration, beginning with type,
      (int, real, vector, row_vector, matrix, unit_vector,
       simplex, ordered, positive_ordered,
       corr_matrix, cov_matrix,
       cholesky_corr, cholesky_cov
  or '}' to close variable declarations>
Error in stanc(filename, allow_undefined = TRUE) : 
  failed to parse Stan model 'foo' due to the above error.

Upvotes: 2

Views: 667

Answers (2)

Bob Carpenter
Bob Carpenter

Reputation: 3753

Stan does not have a proper boolean type. Like C and C++, we use integer value 0 to denote false and value 1 to denote true. To implement a boolean type in Stan, declare it as an integer with a lower bound of 0 (false) and upper bound of 1 (true).

int<lower = 0, upper = 1> c;

R distinguishes integer types from logical types, but allows a lot of conversion. For example, if we define b to be the result of comparing 1 with itself, its value is TRUE and its type is logical (logi in R):

> b = (1 == 1)

> b
[1] TRUE

> str(b)
 logi TRUE

So if I write this Stan program whose behavior differs on a passed boolean,

data {
  int<lower = 0, upper = 1> b;
}
parameters {
  real y;
}
model {
  if (b)
    y ~ normal(0, 1);
  else
    y ~ normal(10, 10);
}

RStan is happy to coerce the boolean, so it's OK to have

fit <- sampling(model, data = list(b = b))

where the value b is a logi type in R.

Upvotes: 2

MDEWITT
MDEWITT

Reputation: 2368

I believe logicals are resolved to their integer values of 0L for FALSE and 1L for TRUE, so using int is appropriate.

Upvotes: 1

Related Questions