Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where in R do I permanently store my custom functions?

Tags:

r

I have several custom functions that I use frequently in R. Rather than souce this file (or parts thereof) in each script, is there some way to add this to a base R file such that they are always available when I use R?

like image 764
Maiasaura Avatar asked Jul 08 '10 18:07

Maiasaura


People also ask

Where are R functions stored?

R packages are a collection of R functions, complied code and sample data. They are stored under a directory called "library" in the R environment. By default, R installs a set of packages during installation. More packages are added later, when they are needed for some specific purpose.

How do I run a custom function in R?

The basic syntax for a custom R function is FunctionName = function(Argument(s)) {Statement(s)} . All functions are assigned a name FunctionName; they end up as objects in your workspace, and are implemented by name. Argument(s) represented the input data objects, which can range for one to several.

What is source on Save in R?

When editing re-usable functions (as opposed to freestanding lines of R) you may wish to set the Source on Save option for the document (available on the toolbar next to the Save icon). Enabling this option will cause the file to automatically be sourced into the global environment every time it is saved.


2 Answers

Yes, create a package. There are numerous tutorials as well as the Writing R Extensions manual that came with your copy of R.

It may seem like too much work at first, but you will probably be glad that you did this in the longer run.

PS And you can then load that package from ~/.Rprofile. For really short code, you can also define it there.

like image 196
Dirk Eddelbuettel Avatar answered Oct 02 '22 22:10

Dirk Eddelbuettel


A package may be overkill for a for a few useful functions. I'd argue there's nothing wrong with explicitly source()ing them as you need them - at least it is explicit so that if you email someone your code, you won't forget to include those other scripts.

like image 35
hadley Avatar answered Oct 02 '22 22:10

hadley