Reputation: 339
I am building a small gibbs sampler but R returns: "Error in [<-
(*tmp*
, i, j, value = NA_real_) : subscript out of bounds".
Problem is with this line:
mu[i,j] <- alpha[i]+beta[i]*(x[j]-mean(x[]))
I just do not understand why?
GS <- function(x){
alpha <- c()
beta <- c()
mu <- matrix()
Y <- matrix ()
for (i in 1:x){
alpha[i] <- rnorm(1,0)
beta[i] <- rnorm(1,0)
for (j in 1:5){
mu[i,j] <- alpha[i]+beta[i]*(x[j]-mean(x[]))
Y[i,j] <- rnorm(1, mu[i,j], 1)
}
Y
}
}
Upvotes: 0
Views: 679
Reputation: 1721
The problem is that you don't initialize your vectors or matrices so the vectors will have lenght 0 and the matrices will only consist of one NA. So you can't write anything to position i since it doesn't exist.
Change
alpha <- c()
beta <- c()
mu <- matrix()
Y <- matrix ()
to
alpha <- numeric(x)
beta <- numeric(x)
mu <- matrix(0,x,5)
Y <- matrix (0,x,5)
Upvotes: 3