0

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

0

1 Answer 1

4

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])
Sign up to request clarification or add additional context in comments.

3 Comments

So seq_along() is the tool I was obviously missing! Many thanks for your help!
The naive method would be 1:length(nc) but this will fail in surprising ways if nc is length 0 or doesn't exist.
I see - I can use seq_along() and seq_len() in most cases when 1:length() seems handy...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.