24

Is there an easy way to view the source of an R package (or a method in a package), from within the interactive environment?

Ari B. Friedman
  • 71,271
  • 35
  • 175
  • 235
pufferfish
  • 16,651
  • 15
  • 56
  • 65

4 Answers4

19

Just enter the name of a function/method without parentheses:

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

See also R-Help Desk - Accessing the Sources in R News Volume 6/4, October 2006.

rcs
  • 67,191
  • 22
  • 172
  • 153
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.
Community
  • 1
  • 1
Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
9

To find out which methods you want to see, write methods(funcOfInterest)

Sometimes it does not suffice to print(funcOfInterest.class). Try print(getAnywhere(funcOfInterest.class)) then.

Iterator
  • 20,250
  • 12
  • 75
  • 111
Karsten W.
  • 17,826
  • 11
  • 69
  • 103
  • 1
    And note that if you're working interactively you don't need the explicit call to `print`. – Dason Nov 02 '12 at 20:00
2

Download package source from https://cloud.r-project.org/src/contrib and open it with your favorite editor. Find the function definition (you can use grep for that). Sometimes you can find a useful introduction as well.

banan3'14
  • 3,810
  • 3
  • 24
  • 47