5

根据文档,predict是一个多态函数,R实际上调用了一个不同的函数,具体取决于作为第一个参数传递的内容。

但是,该文档没有提供有关predict为任何特定类实际调用的函数名称的任何信息。

通常,可以键入函数的名称来获取其源代码,但这不适用于predict.

如果我想在predict对 type 的对象调用时查看函数的源代码glmnet,最简单的方法是什么?

4

2 回答 2

8

您可以使用查找功能getAnywhere

getAnywhere("predict.glmnet")
## A single object matching ‘predict.glmnet’ was found
## It was found in the following places
##   registered S3 method for predict from namespace glmnet
##   namespace:glmnet
## with value
## 
## function (object, newx, s = NULL, type = c("link", "response", 
##     "coefficients", "nonzero", "class"), exact = FALSE, offset, 
##     ...) 
## {
##     type = match.arg(type)
##     if (missing(newx)) {
##         if (!match(type, c("coefficients", "nonzero"), FALSE)) 
##             stop("You need to supply a value for 'newx'")
##     }
##     if (exact && (!is.null(s))) {
##         lambda = object$lambda
##         which = match(s, lambda, FALSE)
##         if (!all(which > 0)) {
##             lambda = unique(rev(sort(c(s, lambda))))
##             object = update(object, lambda = lambda)
##         }
##     }
##     a0 = t(as.matrix(object$a0))
##     rownames(a0) = "(Intercept)"
##     nbeta = rbind2(a0, object$beta)
##     if (!is.null(s)) {
##         vnames = dimnames(nbeta)[[1]]
##         dimnames(nbeta) = list(NULL, NULL)
##         lambda = object$lambda
##         lamlist = lambda.interp(lambda, s)
##         nbeta = nbeta[, lamlist$left, drop = FALSE] * lamlist$frac + 
##             nbeta[, lamlist$right, drop = FALSE] * (1 - lamlist$frac)
##         dimnames(nbeta) = list(vnames, paste(seq(along = s)))
##     }
##     if (type == "coefficients") 
##         return(nbeta)
##     if (type == "nonzero") 
##         return(nonzeroCoef(nbeta[-1, , drop = FALSE], bystep = TRUE))
##     if (inherits(newx, "sparseMatrix")) 
##         newx = as(newx, "dgCMatrix")
##     nfit = as.matrix(cbind2(1, newx) %*% nbeta)
##     if (object$offset) {
##         if (missing(offset)) 
##             stop("No offset provided for prediction, yet used in fit of glmnet", 
##                 call. = FALSE)
##         if (is.matrix(offset) && dim(offset)[[2]] == 2) 
##             offset = offset[, 2]
##         nfit = nfit + array(offset, dim = dim(nfit))
##     }
##     nfit
## }
## <environment: namespace:glmnet>
于 2013-11-06T03:52:12.980 回答
2

调用methods(predict)将显示为特定类定义的所有方法,例如:

> 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*

a 的预测函数glmnet很可能只是predict.glmnet.

于 2013-11-06T03:38:43.333 回答