Reputation: 3456
I am working on an experiment design problem and trying to fit a JAGS
model via R
and r2jags
.
To measure carryover effect, I must access the i-1
element in the list for one of the variables. When i=1
, this variable must return the last item in its list of values. I tried to use an ifelse() but that didn't work.
What I tried:
for (i in 1:Ntotal){
j <- ifelse(i==1,Ntotal,j)
y[i] ~ dnorm(y.hat[i], tau)
y.hat[i] <- mu + beta*a[i] + tau_d*b[i]*period[i] + rho*product[j] + epsilon[i]
epsilon[i] ~ dnorm(0, tau) # gaussian error
}
I get the error:
Error in jags.model(file = "TEMPmodel.txt", data = dataList, n.chains = 3, :
RUNTIME ERROR:
Compilation error on line 7.
Possible directed cycle involving j
Any insight on how to achieve my solution is appreciated.
A simple example in R of what I'm trying to achieve, in case the above is not clear. For variable d
, I must access the preceding element. When starting at the beginning of the index, the preceding element is the last element. For JAGS, I'm not sure how to code my model to do this.
i = 1
exam <- data.frame(a=c(5,6,7), b=c(10,11,12), d=c(20,21,22))
exam$a[i] + exam$b[i] + exam$d[i-1]
Upvotes: 0
Views: 135
Reputation: 2583
There are a couple of problems with this line of code that are worth pointing out:
j <- ifelse(i==1,Ntotal,j)
Firstly, it is inside a for loop so you are trying to re-define node j - so you must index j by i. Secondly, j is being defined as itself - hence the directed cycle message. The following code does what I think you want:
m <- 'model{
for(i in 1:10){
j[i] <- ifelse(i==1, 10, i-1)
}
#monitor# j
}'
runjags::run.jags(m)
However, it might be simpler to make j a dummy variable in R and provide it to JAGS as data i.e.:
m <- 'model{
for(i in 1:N){
new[i] <- j[i]
# Or something else involving j[i]
}
#monitor# new
#data# j, N
}'
N <- 10
j <- c(2:N, 1)
runjags::run.jags(m)
Either way, whenever you refer to j you will need to index it by i - e.g.:
product[j[i]]
Matt
Upvotes: 0