Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

view source code in R [duplicate]

Tags:

r

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?

like image 661
user236215 Avatar asked Aug 14 '10 21:08

user236215


4 Answers

  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.

like image 129
Dirk Eddelbuettel Avatar answered Nov 12 '22 23:11

Dirk Eddelbuettel


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.

like image 29
Marek Avatar answered Nov 13 '22 00:11

Marek


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.

like image 17
user404309 Avatar answered Nov 13 '22 00:11

user404309


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.

like image 7
Eli Sander Avatar answered Nov 13 '22 00:11

Eli Sander