31

How do I view source code in R? For example, for function portfolio.optim

> require(tseries)
> portfolio.optim
function (x, ...) 
UseMethod("portfolio.optim")
<environment: namespace:tseries>

> methods(portfolio.optim)
[1] portfolio.optim.default* portfolio.optim.ts*     

Non-visible functions are asterisked
> portfolio.optim.ts
Error: object 'portfolio.optim.ts' not found
> portfolio.optim.default
Error: object 'portfolio.optim.default' not found

When I install R package locally, does it download source code as well? Where does it store on the computer? Does anyone know?

durron597
  • 31,968
  • 17
  • 99
  • 158
user236215
  • 7,278
  • 23
  • 59
  • 87
  • 3
    See also: Uwe Ligges, "R Help Desk: Accessing the sources" _R News_, 6(4):43-45, October 2006. http://cran.r-project.org/doc/Rnews/Rnews_2006-4.pdf – Brian Diggs Jul 02 '12 at 17:10

4 Answers4

35
  1. In response to Non-visible functions are asterisked, this means that the actual functions that are dispatched on ts or default objects, respectively, are in the tseries namespace but not exported. So just type tseries:::portfolio.optim.default and you see the function code once you specify the full patch including the namespace.

  2. Whether R downloads source or a binary depends on your operating system. In either event, source for the tseries package is available. Reading source code written by experienced coders is a good way to learn.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
24

The getAnywhere function is helpful when you don't know in which namespace is a function.

Described in the manual, or on the function's help page.

isomorphismes
  • 8,233
  • 9
  • 59
  • 70
Marek
  • 49,472
  • 15
  • 99
  • 121
17

What you can do for most of the functions is enter edit(functionname) into the command window in R. Where you fill in functionname with the name.

As a result you can get the source code of the function. However, I tried it for the function portfolio.optim, so there it does not work. Possibly only for standard functions.

user404309
  • 211
  • 1
  • 6
7

If what you want to view is the source for a particular method, you have a couple of options. One is to use debug(portfolio.optim). Then when you run the function on an object, it should go step by step through the method, printing out the code as it goes. Use 'n' to get it to step through, and don't forget to use undebug(portfolio.optim) when you're done.

Alternatively, you can download the source for the package you need, unzip it and look for any files with promising names (this approach is difficult, because the function you're looking for may be written in C!). This is easier than looking for the code in a binary. If you're going this route, the code should just be available in a compressed folder wherever you downloaded to.

Eli Sander
  • 1,228
  • 1
  • 13
  • 29