我试图从教科书ISLR运行代码。这是关于最佳子集选择:
library(ISLR) #contain data Hitters
library(leaps) #use regsubsets
regfit.full=regsubsets(Salary~.,Hitters)
predict(regfit.full)
然后R显示错误:
Error in UseMethod("predict") :no applicable method for 'predict' applied to an object of class "regsubsets"
我正在使用Windows RStudio版本0.99.893,R-3.2.4revised-win。 我真的不知道为什么“预测”不适用于“regsubsets”。
这是我第一次在这里提问,请让我知道我能做些什么来帮助解决这个问题。非常感谢提前!
--------------------更新-------------------------- -------------
感谢李哲元,我明白了。 regsubsets没有预测方法。我们需要自己写一个。以下是来自互联网的内容:
predict.regsubsets = function(object, newdata, id, ...) {
form = as.formula(object$call[[2]])
mat = model.matrix(form, newdata)
coefi = coef(object, id = id)
mat[, names(coefi)] %*% coefi
}
其他信息:
> sessionInfo()
R version 3.2.4 Revised (2016-03-16 r70336)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] ISLR_1.0 leaps_2.9
loaded via a namespace (and not attached):
[1] tools_3.2.4
> methods(predict)
[1] predict.ar* predict.Arima* predict.arima0* predict.glm
[5] predict.HoltWinters* predict.lm predict.loess* predict.mlm*
[9] predict.nls* predict.poly* predict.ppr* predict.prcomp*
[13] predict.princomp* predict.smooth.spline* predict.smooth.spline.fit* predict.StructTS*
see '?methods' for accessing help and source code
> regfit.full
Subset selection object
Call: regsubsets.formula(Salary ~ ., Hitters)
19 Variables (and intercept)
Forced in Forced out
AtBat FALSE FALSE
Hits FALSE FALSE
HmRun FALSE FALSE
Runs FALSE FALSE
RBI FALSE FALSE
Walks FALSE FALSE
Years FALSE FALSE
CAtBat FALSE FALSE
CHits FALSE FALSE
CHmRun FALSE FALSE
CRuns FALSE FALSE
CRBI FALSE FALSE
CWalks FALSE FALSE
LeagueN FALSE FALSE
DivisionW FALSE FALSE
PutOuts FALSE FALSE
Assists FALSE FALSE
Errors FALSE FALSE
NewLeagueN FALSE FALSE
1 subsets of each size up to 8
Selection Algorithm: exhaustive