【发布时间】:2013-11-17 04:33:34
【问题描述】:
根据文档,predict 是R 中的一个多态函数,根据作为第一个参数传递的内容实际调用不同的函数。
但是,该文档没有提供有关 predict 为任何特定类实际调用的函数名称的任何信息。
通常,可以键入函数的名称来获取其来源,但这不适用于predict。
如果我想在glmnet 类型的对象上调用predict 函数时查看源代码,最简单的方法是什么?
【问题讨论】:
标签: r
根据文档,predict 是R 中的一个多态函数,根据作为第一个参数传递的内容实际调用不同的函数。
但是,该文档没有提供有关 predict 为任何特定类实际调用的函数名称的任何信息。
通常,可以键入函数的名称来获取其来源,但这不适用于predict。
如果我想在glmnet 类型的对象上调用predict 函数时查看源代码,最简单的方法是什么?
【问题讨论】:
标签: r
调用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。
【讨论】:
library(glmnet) 之后,没有那个名字的方法。这就是为什么我很好奇。一般来说,有没有办法告诉给定特定对象实际调用了哪些预测方法?
glmnet 包,似乎 predict.glmnet 没有导出到全局命名空间中,因此访问起来有点困难,但您可以使用glmnet:::predict.glmnet,并查看使用methods(class=glmnet)定义的方法
您可以使用 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>
【讨论】: