> methods(length)
[1] length.pdf_doc* length.POSIXlt see '?methods' for accessing help and source code > length.POSIXlt function (x) length(x[[1L]]) <bytecode: 0x00000000111d75b0> <environment: namespace:base>-------------------------------------------------------------------------
方法一:直接写函数名称,如在R中查看回归分析代码:
- lm
复制代码
直接可以查看到- function (formula, data, subset, weights, na.action, method = "qr",
- model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE,
- contrasts = NULL, offset, ...)
- {
- ret.x <- x
- ret.y <- y
- cl <- match.call()
- mf <- match.call(expand.dots = FALSE)
- m <- match(c("formula", "data", "subset", "weights", "na.action",
- "offset"), names(mf), 0L)
- mf <- mf[c(1L, m)]
- mf$drop.unused.levels <- TRUE
- mf[[1L]] <- quote(stats::model.frame)
- mf <- eval(mf, parent.frame())
- if (method == "model.frame")
- return(mf)
- else if (method != "qr")
- warning(gettextf("method = '%s' is not supported. Using 'qr'",
- method), domain = NA)
- mt <- attr(mf, "terms")
- y <- model.response(mf, "numeric")
- w <- as.vector(model.weights(mf))
- if (!is.null(w) && !is.numeric(w))
- stop("'weights' must be a numeric vector")
- offset <- as.vector(model.offset(mf))
- if (!is.null(offset)) {
- if (length(offset) != NROW(y))
- stop(gettextf("number of offsets is %d, should equal %d (number of observations)",
- length(offset), NROW(y)), domain = NA)
- }
- if (is.empty.model(mt)) {
- x <- NULL
- z <- list(coefficients = if (is.matrix(y)) matrix(, 0,
- 3) else numeric(), residuals = y, fitted.values = 0 *
- y, weights = w, rank = 0L, df.residual = if (!is.null(w)) sum(w !=
- 0) else if (is.matrix(y)) nrow(y) else length(y))
- if (!is.null(offset)) {
- z$fitted.values <- offset
- z$residuals <- y - offset
- }
- }
- else {
- x <- model.matrix(mt, mf, contrasts)
- z <- if (is.null(w))
- lm.fit(x, y, offset = offset, singular.ok = singular.ok,
- ...)
- else lm.wfit(x, y, w, offset = offset, singular.ok = singular.ok,
- ...)
- }
- class(z) <- c(if (is.matrix(y)) "mlm", "lm")
- z$na.action <- attr(mf, "na.action")
- z$offset <- offset
- z$contrasts <- attr(x, "contrasts")
- z$xlevels <- .getXlevels(mt, mf)
- z$call <- cl
- z$terms <- mt
- if (model)
- z$model <- mf
- if (ret.x)
- z$x <- x
- if (ret.y)
- z$y <- y
- if (!qr)
- z$qr <- NULL
- z
- }
复制代码
优点:直接简单。
缺点:并非所有的函数都能通过此方法得到。原因:R是面向对象设计的程序语言。方法二:与方法一类似,用函数page(),不过,结果在另一个窗口显示。方法三:与方法二类似,用函数edit()。方法四:对于计算方法不同的函数,要用methods()来定义具体的查看对象,如查看函数mean代码,用方法一只能查到- function (x, ...)
- UseMethod("mean")
复制代码
无法得到具体的代码。此时要有methods()来查找mean具体的对象
- methods(mean)
复制代码
此时,结果是 [1] mean.Date mean.default mean.difftime mean.POSIXct mean.POSIXlt 要查看具体名称,如mean.default的代码,直接用代码- mean.default
复制代码
可以看到mean.default的源代码- function (x, trim = 0, na.rm = FALSE, ...)
- {
- if (!is.numeric(x) && !is.complex(x) && !is.logical(x)) {
- warning("argument is not numeric or logical: returning NA")
- return(NA_real_)
- }
- if (na.rm)
- x <- x[!is.na(x)]
- if (!is.numeric(trim) || length(trim) != 1L)
- stop("'trim' must be numeric of length one")
- n <- length(x)
- if (trim > 0 && n) {
- if (is.complex(x))
- stop("trimmed means are not defined for complex data")
- if (anyNA(x))
- return(NA_real_)
- if (trim >= 0.5)
- return(stats::median(x, na.rm = FALSE))
- lo <- floor(n * trim) + 1
- hi <- n + 1 - lo
- x <- sort.int(x, partial = unique(c(lo, hi)))[lo:hi]
- }
- .Internal(mean(x))
- }
复制代码
注意:1. 对于程序包里的函数,需要先调用函数所在的包。 2.对于methods()得出的类函数中带星号标注的源代码是看不到的。 3.对于非类函数,不能用此方法。方法五:对于方法四中methods()得出的类函数中带星号标注的源代码,用函数getAnywhere(),如查找predict函数的源代码。- methods(predict)
复制代码
结果显示:
[1] predict.ar* predict.Arima* predict.arima0* predict.glm predict.HoltWinters* predict.lm [7] predict.loess* predict.mlm* predict.nls* predict.poly* predict.ppr* predict.prcomp* [13] predict.princomp* predict.smooth.spline* predict.smooth.spline.fit* predict.StructTS* 若用命令predict.Arima查看predict.Arima源代码。结果显示: 错误: 找不到对象'predict.Arima' 此时,用- getAnywhere(predict.Arima)
复制代码
这样就可以查看到predict.Arima的源代码。- function (object, n.ahead = 1L, newxreg = NULL, se.fit = TRUE,
- ...)
- {
- myNCOL <- function(x) if (is.null(x))
- 0
- else NCOL(x)
- rsd <- object$residuals
- xr <- object$call$xreg
- xreg <- if (!is.null(xr))
- eval.parent(xr)
- else NULL
- ncxreg <- myNCOL(xreg)
- if (myNCOL(newxreg) != ncxreg)
- stop("'xreg' and 'newxreg' have different numbers of columns")
- class(xreg) <- NULL
- xtsp <- tsp(rsd)
- n <- length(rsd)
- arma <- object$arma
- coefs <- object$coef
- narma <- sum(arma[1L:4L])
- if (length(coefs) > narma) {
- if (names(coefs)[narma + 1L] == "intercept") {
- xreg <- cbind(intercept = rep(1, n), xreg)
- newxreg <- cbind(intercept = rep(1, n.ahead), newxreg)
- ncxreg <- ncxreg + 1L
- }
- xm <- if (narma == 0)
- drop(as.matrix(newxreg) %*% coefs)
- else drop(as.matrix(newxreg) %*% coefs[-(1L:narma)])
- }
- else xm <- 0
- if (arma[2L] > 0L) {
- ma <- coefs[arma[1L] + 1L:arma[2L]]
- if (any(Mod(polyroot(c(1, ma))) < 1))
- warning("MA part of model is not invertible")
- }
- if (arma[4L] > 0L) {
- ma <- coefs[sum(arma[1L:3L]) + 1L:arma[4L]]
- if (any(Mod(polyroot(c(1, ma))) < 1))
- warning("seasonal MA part of model is not invertible")
- }
- z <- KalmanForecast(n.ahead, object$model)
- pred <- ts(z[[1L]] + xm, start = xtsp[2L] + deltat(rsd),
- frequency = xtsp[3L])
- if (se.fit) {
- se <- ts(sqrt(z[[2L]] * object$sigma2), start = xtsp[2L] +
- deltat(rsd), frequency = xtsp[3L])
- return(list(pred = pred, se = se))
- }
- else return(pred)
- }
复制代码
方法六:直接上CRAN 下载源代码包
流程如下:
1) 登入R主页 http://www.r-project.org/ ,点击 Download 下的CRAN;
2) 选择一个镜像;
3) 里面的Source Code for all Platforms下有各种源码了,对于程序包,点packages;
4) 点选择项Table of available packages, sorted by name;
5) 找到你你想要的包,点击看Package source这一项,用tar.gz封装的,下载解压后就能看见源代码了。
很多函数的核心是用C或FORTRAN等写的,利用.C(),.FORTRAN()等函数调用。这种做法是出于计算效率的考虑。
最后,如果真的想阅读组成R系统本身的源代码,在各个CRAN中均有下载。都是精心挑选过的,是学习的好材料。同时,你可以看到R系统内部是如何构成的,对于高效使用R有至关重要的作用。
欢迎大家多多和我交流,共同进步。