问题描述
在下面的代码中,我试图创建一个矩阵,该矩阵将列出每个城市的opt.lam.在运行循环后,前两个城市始终可以正常工作,然后在此之后的任何城市我都会遇到错误.
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.
这是我得到的错误. (coefmatrix可以正常工作,只是lambdamatrix会产生此错误).
This is the error that I get. (coefmatrix works fine, it's just the lambdamatrix that produces this error).
[<-
(*tmp*
,,i,value = c(0.577199381062121,0.577199381062121,: 下标超出范围
Error in [<-
(*tmp*
, , i, value = c(0.577199381062121, 0.577199381062121, : subscript out of bounds
这是我的代码:
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]
}`
推荐答案
在[,i]
中,i
是列索引器(而[i,]
将是行索引器).
In [,i]
, i
is the column indexer (whereas [i,]
would be a row indexer).
由于您将lambdamatrix
定义为matrix(nrow = n, ncol = 2)
,因此,一旦经过i=2
,便要求输入不存在的列.
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.
这篇关于错误[[< -`(`* tmp *`,,下标超出范围下标超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!