如何查看特定`predict`函数的源代码?

时间:2013-11-06 03:35:15

标签: r

根据文档,predictR中的多态函数,实际调用的函数取决于作为第一个参数传递的内容。

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

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

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

2 个答案:

答案 0 :(得分:7)

您可以使用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>

答案 1 :(得分: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*

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

相关问题