rfunction

how to make a function available at start up in R


I have a user defined function in R

blah=function(a,b){
something with a and b
}

is it possile to put this somewhere so that I do not need to remember to load in the workspace every time I start up R? Similar to a built in function like

summary(); t.test(); max(); sd()

Solution

  • You can put the function into your .Rprofile file.

    However, be very careful with what you put there, since it essentially makes your code non-reproducible — it now depends on your .Rprofile:

    Let’s say you have an R code file performing some analysis, and the code uses the function blah. Executing the code on any other system will fail due to the non-existence of the blah function.

    As a consequence, this file should only contain system-specific setup. Don’t define helper functions in there — or if you do, make them defined only in interactive sessions, so that you have a clear environment when R is running a non-interactive script:

    if (interactive()) {
        # Helper functions go here.
    }
    

    And if you find yourself using the same helper functions over and over again, bundle them into packages (or modules) and reuse those.