32

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?

1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I am unable to display source code for function lu in package Matrix. Can you please take a look?
25

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.

Comments

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.

2 Comments

Why the downvote? I've tested this and it works on a library function.
Brings up a nice window in RStudio. +1 !
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.

1 Comment

wow. thanks you very much for this debug function. it's awesome!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.