Search code examples
bayesianjags

Nested indexing VS. nested for loop in Bayesian hierarchical model specification


I come across two methods of specifying Bayesian hierarchical model in the book "Bayesian methods: a social and behavioural approach" (2015), third edition by Jeff Gill.

The three examples from the book (as below) are about Bayesian hierarchical models. Key differences in the models have been circled in red:

In Example 1, the nesting structure is expressed through the nested indexing alpha[state.id[i]]. The two for loops are specified separately. However, in Example 2 and 3, the hierarchical structures are specified through nested for loop rather than nested indexing. Besides, there are i and j appearing within the same square brackets (Q[i,j] in Example 2 and mu[i,j] in Example 3), as contrast to Example 1 where only one index (either i or j) appears in the square brackets.

MY QUESTION: What are the differences between nested indexing VS. nested for loop when specifying the Bayesian hierarchical model? Can Example 1 be modelled in a way similar to Example 2 and 3 or vice versa? How can I choose between the two methods?

I will provide you the full example if you feel more comfortable knowing details of the examples.

Thank you!

Example 1

Example 2

Example 3


Solution

  • Yes, example 1 can be written similar to example 2 and 3 and vice versa. This is simplest if each value of the first iterator has the same values of the second iterator. Otherwise you will end up with something like

    for(i in 1:VALUE) {
      for (j in 1:TIME[i]){
        ...
      }
    }
    

    but then using a matrix (or more generally an array), e.g. Q in example 2 and mu in example 3, is not as natural.

    I typically use the nested indexing approach since I typically store my data in an R data.frame which is easily amenable to the nested indexing approach. In the first example, state.id, contracting, gov.influence, etc. would all be columns of the data.frame. I also find the code easier to read in the nested indexing, but I could probably improve my code in the situations where I use nested for loops by creating informative iterators.

    Since you can write either example in either fashion, which you choose ends up being a matter of preference.