如何将逻辑 R 对象传递给 Stan 文件中的数据块

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

如果数据列表包含逻辑变量x,即x=TRUEx=FALSE。 那么如何在Stan文件中声明这样一个变量呢?

例如,如果 R 对象 x 是整数,则

data{

int <lower=0>x;

}

我想知道它的逻辑版本。我猜

data{

               bool x;

    }

它不能像下面那样工作;

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.

我认为逻辑值解析为整数值 0L 表示 FALSE,1L 表示 TRUE,因此使用 int 是合适的。

Stan 没有合适的布尔类型。与 C 和 C++ 一样,我们使用整数值 0 表示假,值 1 表示真。要在 Stan 中实现布尔类型,请将其声明为整数,下限为 0(假),上限为 1(真)。

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

R 将整数类型与逻辑类型区分开来,但允许进行大量转换。例如,如果我们定义 b 为 1 与自身比较的结果,则其值为 TRUE 并且其类型为逻辑(logi in R):

> b = (1 == 1)

> b
[1] TRUE

> str(b)
 logi TRUE

所以如果我编写这个 Stan 程序,其行为在传递的布尔值上有所不同,

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

RStan 很乐意强制转换布尔值,所以可以

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

其中值 b 是 R 中的 logi 类型。