Search code examples
vectorwinbugsr2winbugs

Replicating R's prod() function in WinBUGS


Using WinBUGS, how can I calculate the product of all values in a single vector?

I have tried using a for loop over the same vector.

For example:

In R, if A <- [1,2,3,4], prod(A) = 24.

However,

in BUGS, if a <- 2 , and for (i in 1:n){ a <- a * A[i] }, this loop cannot work because 'a' is defined twice.


Solution

  • Hi and welcome to the site!

    Remember that BUGS is a declarative syntax and not a programming language, so you cannot over-write variable values as you expect to be able to in a language such as R. So you need to create some intermediate nodes to do what you calculate.

    If you have the following data:

    A <- [1,2,3,4]
    nA <- 4
    

    Then you can include in your model:

    sumlogA[1] <- 0
    for(i in 1:nA){
        sumlogA[i+1] <- sumlogA[i] + log(A[i])
    }
    prodA <- exp(sumlogA[nA+1])
    

    Notice that I am working on the log scale and then take the exponent of the sum - this is mathematically equivalent to the product but is a much more computationally stable calculation.

    Hope that helps,

    Matt