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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With