# Reading in array of vectors

I want to check that my R data are reading correctly into Stan. In Stan I would like to work with arrays of length V made up of vectors of length D. Following past guidance this is said to be VxD array so I wrote that into my data list in R, as below:

``````stan_data <- list(
D = 3,
V = 2,
dat = array(c(c(1,2,3), c(1,2,3)), dim=c(V,D))
)
``````

prints as

``````      [,1] [,2] [,3]
[1,]    1    3    2
[2,]    2    1    3
``````

and does not look great in R but, but I have read elsewhere that to read into an array of vectors VxD that is how the dims should be written in R.

For Stan code I have

``````write("data {
int<lower=0> D; // vector length inside array
int<lower=0> V; // length of array
array[V] vector[D] dat;
}
generated quantities {
print(dat);
}",

"test.stan")
``````

Which prints the same as the R input as `[[1,3,2],[2,1,3]] `

But if I try to switch the order of the input array to read more true to expectations:

``````stan_data <- list(
D = 3,
V = 2,
dat = array(c(c(1,2,3), c(1,2,3)), dim=c(D,V))
)
``````

with output

``````     [,1] [,2]
[1,]    1    1
[2,]    2    2
[3,]    3    3
``````

and run with the same Stan code I get the error `mismatch in dimension declared and found in context; processing stage=data initialization; variable name=dat; position=0; dims declared=(2,3); dims found=(3,2)`.

How can I rearrange things to get my expected Stan output of `[[1,2,3],[1,2,3]] `?

I believe you can just pass a list of vectors as the input:

``````library(rstan)
#> rstan (Version 2.21.5, GitRev: 2e1f913d3ca3)
#> For execution on a local, multicore CPU with excess RAM we recommend calling
#> options(mc.cores = parallel::detectCores()).
#> To avoid recompilation of unchanged Stan programs, we recommend calling
#> rstan_options(auto_write = TRUE)
#> Do not specify '-march=native' in 'LOCAL_CPPFLAGS' or a Makevars file

modcode <- "
functions {
vector[] rtn_array(vector[] vec_array) {
return vec_array;
}
}
"
expose_stan_functions(stanc(model_code = modcode))

rtn_array(list(c(1,2,3),c(4,5,6)))
#> []
#>  1 2 3
#>
#> []
#>  4 5 6
``````

Created on 2022-04-26 by the reprex package (v2.0.1)