rarraysmatrixvectorrstan

Rstan: How to read in multiple vectors from R to Stan


Say I have some vectors in Stan

vector[100] mu[20]

This means mu is 20 vectors each of length 100.

Do I read this in as mu = martix(NA,nrow=100,ncol=20) or as mu = array(NA,dim=c(100,20)) from R? (I hope I'm not getting the dimensions mixed up)

Or is incorrect and do you this differently?


Solution

  • So you have two options to provide the matrix/array or a list of vectors. In your example you have to change the order for rows and columns.

    The rstan error messages are clear so you will know if something goes wrong with dimensions.

    library(rstan)
    # dummy parameters
    scode <- "
    data {
      vector[100] mu[20];
    }
    parameters {
      real y[2]; 
    }
    "
    # Both fit pass without errors
    fit1 <- stan(
      model_code = scode,
      data = list(mu = matrix(rnorm(20 * 100), nrow = 20, ncol = 100))
    ) 
    fit2 <- stan(
      model_code = scode, 
      data = list(mu = lapply(1:20, function(x) rnorm(100)))
    )