I have a loop that works completely well by itself. What I essentially want to do is repeat that same loop 100 more times to fill a matrix that 100x bigger than the original matrix.
nsite - 267
nyear - 14
#pred.occ is a data.frame of 14 columns and 267 rows
z_pred <- array(NA, dim = c(nsite, 4*100)) # my matrix
for (i in 1:100) {
# Generate presence/absence (i.e., the truth) in subsequent years
for(t in 11:nyear){
z_pred[,t*i] <- rbinom(n = nsite, size = 1, prob = pred.occ[,11:nyear])
}
sum_occupancy <- apply(z_pred, 2, sum) / nsite # predicted occupancy proportion
}
The error I am getting is "subscript out of bounds" but I tried to modify but I am not sure where I am going wrong.
CodePudding user response:
I think there are a number of things going on here.
- First, your matrix z_pred has dimensions 267,400, but your call in the innermost loop tries to assign to columns of this matrix that don't exist. For example, when
t=11
andi=40
you will try to assign to column 440. - You are trying to pass a dataframe of size 267x4 to the prob param of the rbinom function. I think what you want to do here is pass the 267 probabilities in column
t
Here is a revised version that might help you
z_pred <- array(NA, dim = c(nsite, 4*100)) # my matrix
for (i in 1:100) {
# Generate presence/absence (i.e., the truth) in subsequent years
for(t in 11:nyear) {
z_pred[,100*(t-11) i] <- rbinom(n = nsite, size = 1, prob =pred.occ[,t])
}
sum_occupancy <- apply(z_pred, 2, sum) / nsite # predicted occupancy proportion
}