Error in `[<-`(`*tmp*`, , subscript out of boun

2019-05-21 07:29发布

问题:

In the following code, I am trying to create a matrix that will list off the opt.lam for each city. Upon running the loop, the first two cities always work, and then I get an error for any cities after that.

This is the error that I get. (coefmatrix works fine, it's just the lambdamatrix that produces this error).

Error in [<-(*tmp*, , i, value = c(0.577199381062121, 0.577199381062121, : subscript out of bounds

Here is my code:

lambdamatrix <- matrix(nrow=n,ncol=2)
rownames(lambdamatrix) <- cityIDs
colnames(lambdamatrix) <- c("lambda.min","lambda.1se")
for (i in 1:n) {
  data <- subset(simdata, city==cityIDs[i])
  x <- as.matrix(data.frame(data[,3:24]))
cvfit <- cv.glmnet(x, data$Y, family="poisson", offset=log(data$population))
opt.lam <- c(cvfit$lambda.min, cvfit$lambda.1se)
fit <- glmnet(x, data$Y, family= "poisson", offset=log(data$population))
abline(plot(fit, "lambda", label= TRUE, 
            main = cityIDs[i]), v=log(opt.lam), lty=2, lwd=3, 
                                    col=c("red","dark green"))
coefmatrix[,i] <- coef(fit, s=opt.lam[1])[1:23]
lambdamatrix[,i] <- c(cvfit$lambda.min, cvfit$lambda.1se)[1:n]
}`

回答1:

In [,i], i is the column indexer (whereas [i,] would be a row indexer).

Since you define lambdamatrix as matrix(nrow = n, ncol = 2), once you get past i=2 you are asking for columns that don't exist.