24

是否有一种简单的方法可以从交互式环境中查看 R 包(或包中的方法)的源代码?

4

4 回答 4

19

只需输入不带括号的函数/方法的名称:

R> base::rev.default 
function (x) 
if (length(x)) x[length(x):1L] else x
<environment: namespace:base>

另请参阅R-Help Desk - Accessing the Sources in R News 第 6/4 卷,2006 年 10 月

于 2009-11-24T09:07:44.763 回答
15

How you find the source code depends on the type of function. See my answer to this related question.

As rcs pointed out, if you want to specify a package, you can use ::.

> lattice::xyplot
function (x, data, ...) 
UseMethod("xyplot")
<environment: namespace:lattice>

Not all functions from a package will be exported (i.e. made publically available); for these you need to use :::.

> lattice::xyplot.formula
Error: 'xyplot.formula' is not an exported object from 'namespace:lattice'

> lattice:::xyplot.formula
function (x, data = NULL, allow.multiple = is.null(groups) || 
    outer, outer = !is.null(groups), auto.key = FALSE, aspect = "fill", 
    panel = lattice.getOption("panel.xyplot"), prepanel = NULL, 
    scales = list(), strip = TRUE, groups = NULL, xlab, xlim, 
    ylab, ylim, drop.unused.levels = lattice.getOption("drop.unused.levels"), 
    ..., lattice.options = NULL, default.scales = list(), subscripts = !is.null(groups), 
    subset = TRUE) 
{
    formula <- x
    dots <- list(...)
# etc.
于 2009-11-24T16:44:11.770 回答
9

要找出您想要查看的方法,请编写methods(funcOfInterest)

有时它是不够的print(funcOfInterest.class)。那就试试print(getAnywhere(funcOfInterest.class))吧。

于 2009-11-24T15:45:19.317 回答
2

从https://cloud.r-project.org/src/contrib下载包源并使用您喜欢的编辑器打开它。找到函数定义(您可以使用grep它)。有时您也可以找到有用的介绍。

于 2018-10-17T22:36:37.883 回答