我正在尝试创建一个函数来交叉验证R中的线性回归模型。我有一些代码可以在线工作,但是当我将其编写为函数时,会出现以下错误:
“错误:“符号”类型的对象不可子集化”
问题所在的行是:
pred_x = predict.regsubsets(best_subset, dfcv[folds == j, ], id = i)
函数在这里:
cross_validate <-function(dfcv,nbr.indep,nbr.folds=10)
{
#nbr.folds=10
#dfcv = df.train
#nbr.indep = indy.count
k <- nbr.folds
set.seed(1)
folds <- sample(1:k, nrow(dfcv), replace = TRUE)
#table.folds<-table(folds)
error.matrix <- matrix(NA, k,nbr.indep, dimnames = list(NULL,
paste(1:nbr.indep)))
for(j in 1:k) {
# perform best subset on rows not equal to j
best_subset <- regsubsets(dep ~ ., dfcv[folds != j,], nvmax =
nbr.indep)
# perform cross-validation
for( i in 1:nbr.indep) {
pred_x = predict.regsubsets(best_subset, dfcv[folds == j, ], id = i)
error.matrix[j, i] <- mean((dfcv$dep[folds == j] - pred_x)^2)
}
}
mcve<-colMeans(error.matrix)
return(mcve)
}
有人知道为什么它会出错吗?
谢谢