rjagsrjagsr2jags

slicing a vector shows error our of range


I have this part of my jags code. I really can't see where the code gets out of the range. Can anyone please see any error that I can't recognize? These are the data sizes.

N = 96

L = c(4,4,4,4,4)

length(media1) = 96

length(weights1) = 4

      for(t in 1:N){
        current_window_x <- ifelse(t <= L[1], media1[1:t], media1[(t - L[1] + 1):t])
        t_in_window <- length(current_window_x)
        new_media1[t] <- ifelse(t <= L[1], inprod(current_window_x, weights1[1:t_in_window]), 
        inprod(current_window_x, weights1))
      }

The error is (where line 41 correspond to the first line in the loop)

      Error in jags.model(model.file, data = data, inits = init.values, n.chains = n.chains,  : 
      RUNTIME ERROR:
      Compilation error on line 41.
      Index out of range taking subset of  media1

Solution

  • I actually just happened on to the answer here earlier today for something I was working on. The answer is in this post. The gist is that ifelse() in jags is not a control flow statement, it is a function and both the TRUE and FALSE conditions are evaluated. So, even though you are saying to use media1[1:t] if t<=L[1], the FALSE condition is also being evaluated which produces the error.

    The other problem once you're able to fix that is that you're re-defining the parameter current_window_x, which will throw an error. I think the easiest way to deal with the variable window width is just to hard code the first few observations of new_media and then calculate the remaining ones in the loop, like this:

    new_media[1] <- media1[1]*weights1[1]
    new_media[2] <- inprod(media1[1:2], weights1[1:2])
    new_media[3] <- inprod(media1[1:3], weights1[1:3])
    for(t in 4:N){
      new_media[t] <- inprod(media1[(t - L[1] + 1):t], weights1)
    }