# Hierarchical model with subject-specific (spatial) correlation

**URL:** <https://discourse.mc-stan.org/t/hierarchical-model-with-subject-specific-spatial-correlation/8569>\
**Category:** Modeling\
**Created:** [April 22, 2019, 11:23am UTC](https://discourse.mc-stan.org/t/hierarchical-model-with-subject-specific-spatial-correlation/8569 "2019-04-22T11:23:10Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![macks](https://avatars.discourse-cdn.com/v4/letter/m/67e7ee/32.png) [@macks](https://discourse.mc-stan.org/u/macks)\
**Post date:** [April 22, 2019, 11:23am UTC](https://discourse.mc-stan.org/t/hierarchical-model-with-subject-specific-spatial-correlation/8569/1 "2019-04-22T11:23:10Z")

</div>

Dear all,

I would like to develop a stan-model which I previously implemented as a linear mixed effects model using the nlme package in R. I have longitudinal data with up to `n_k` datapoints from `k` subjects. Means should be random among subjects and relationships between the individual points should be described via a multivariate normal distribution with correlations depending on the distance (in time) between the datapoints.

So basically the model would be a mixed model with random intercepts and spatial correlation. It is slightly more complicated since the correlation should further depend on covariates, so ideally I would define a function which sets up the covariance matrix for each subject individually (varying number of points per subject, different times and covariates) depending on a small set of estimated variance/covariance parameters. For the nlme package, I wrote a function which generates the subject-wise covariance matrix, but I don’t really have an idea how to do this with stan. Before extensive trial and error, is this generally feasible with stan and are there any tutorials on this matter I didn’t come across yet?

Thanks a lot in advance  
Max

---

<div class="post-metadata">

**Author:** ![martinmodrak](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/martinmodrak/32/133_2.png) [@martinmodrak](https://discourse.mc-stan.org/u/martinmodrak)\
**Post date:** [April 25, 2019, 7:10am UTC](https://discourse.mc-stan.org/t/hierarchical-model-with-subject-specific-spatial-correlation/8569/2 "2019-04-25T07:10:03Z")

</div>

It should generally be feasible unless your dataset is quite large.

I believe something at least close to what you aim for should be possible with the `brms` package (checkout `cor_car` and `cor_sar`), but I didn’t find a good tutorial. This would let you avoid writing Stan code yourself and generally has a more relaxed learning curve. If `brms` won’t be enough, I would suggest you start with the CAR code at [https://github.com/mbjoseph/CARstan](https://github.com/mbjoseph/CARstan) and rewrite the code for the precisions/covariance matrix.
