Reputation: 195
I am struggling with an output allocation issue in a "for" loop: I generate an empty matrix ("results") with appropriate (is it not???) dimensions where the loop should allocate the output from the function (pls), but I am getting an error... Here is the code:
library(pls)
set.seed(10000)
mat <- replicate(100, rnorm(100))
y <- as.matrix(mat[,1], drop=F)
x <- mat[,2:100]
min.nc <- 3
max.nc <- 8
nc <- seq(min.nc, max.nc)
results <- matrix(NA, length(nc), 1)
for(q in nc) {
pls <- plsr(y ~ x, ncomp = q)
results[q,] <- RMSEP(pls, intercept=F, estimate="train")$val[1,1,q]
}
The error message after running the "for" loop says:
Error in `[<-`(`*tmp*`, q, , value = 0.329631604369802) :
subscript out of bounds
...which I don't understand, since the iterator "nc" has exactly the size of "length(nc)". Any ideas?
Many thanks for your time and help!
Chega
Upvotes: 0
Views: 323
Reputation: 43245
Your q
is 3:8 and your matrix results
is 1:6. Thus, when it tries to assign results[q,]
when q > 6
you get this error.
> results[7,]
Error in results[7, ] : subscript out of bounds
The value of q
is each value of nc
rather than seq_along(nc)
.
for (q in nc) print(q)
Versus
for (q in seq_along(nc)) print(nc[q])
Upvotes: 4