1

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.

1 Answers1

1

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

Matt Denwood
  • 2,537
  • 1
  • 12
  • 16
  • Thank you very much @MattDenwood. Please can you clarify why prod() is used in WinBUGS code - and works - in academic text examples such as pg. 165 of _Bayesian Population Analysis in WinBUGS_ (Kery & Schaub)? [Link] (https://books.google.co.uk/books?id=kd4JGs44ap4C&pg=PA365&lpg=PA365&dq=prod+winbugs&source=bl&ots=VV_5dnK19o&sig=88nootnRXD5S_i7e180b9VGToSU&hl=en&sa=X&ved=2ahUKEwiA0cfTvIDeAhWjgVwKHYfZBtQQ6AEwB3oECAAQAQ#v=onepage&q=prod%20winbugs&f=false) – emperorgoose Oct 12 '18 at 08:35
  • As far as I know this would never have worked in WinBUGS, but it would work in OpenBUGS or JAGS so perhaps the code was intended for use with the newer software. To be honest I haven’t used WinBUGS (or OpenBUGS) in years as it is no longer being developed. JAGS is still being developed and is also cross platform, which is important to me. – Matt Denwood Oct 12 '18 at 09:03
  • Yes I fully agree with you about the importance of using up-to-date software. I was interested to find that the prod() function works in WinBUGS as an undocumented capability, but is documented in both OpenBUGS and JAGS as you say. It must have been added after the manual was written. Thank you for your reply! – emperorgoose Oct 12 '18 at 09:17