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

25,381

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.

Share:
25,381
Admin
Author by

Admin

Updated on March 24, 2020

Comments

  • Admin
    Admin about 4 years

    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]
    }`