I was trying to run codes from textbook ISLR. It is about Best Subset Selection:
library(ISLR) #contain data Hitters
library(leaps) #use regsubsets
regfit.full=regsubsets(Salary~.,Hitters)
predict(regfit.full)
Then R showed error:
Error in UseMethod("predict") :no applicable method for 'predict' applied to an object of class "regsubsets"
I am using Windows RStudio Version 0.99.893, R-3.2.4revised-win. I really have no idea why the "predict" cannot apply to "regsubsets".
This is the first time I ask a question here, please let me know what I can do to help solve this problem. Many thanks in advance!
--------------------update---------------------------------------
Thanks to Zheyuan Li, I figured it out. There is no predict method for regsubsets. We need to write one ourselves. Below is one from internet:
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
}
other info:
> 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