Customizing R: startup script

(This article was first published on macsci, and kindly contributed to R-bloggers)


While R is certainly a great tool, some functions seem to be missing. Take for instance the standard error, for some reason there is no standard function included, while you would expect se(x) to work. Therefore I usually include a couple of functions, like a standard error, a correct round() function (the standard function round(2.5) gives 2 as a result), and some other functions in my R-scripts.
Last week, I decided to come up with a constructive solution. When R starts up, it loads an .Rprofile file in your home directory (if it exists), and executes a .First() function. The solution is therefore really easy, you put such a file in your home directory (and rename it to .Rprofile, note that Snow Leopard might try to resist this, use the terminal in that case: mv dotRprofile .Rprofile), which sources another file:

.First <- function(){
    cat(“\nWelcome to R!\n”,sep=””)
        cat(“RbasicFunctions.r was loaded, providing the following functions:\n\n”,sep=””)

As you can see, this file sources ‘RbasicFunctions.r” if it exists, and executes print.functions(). RbasicFunctions.r is the file containing my functions, and in that file there’s also the print.functions() that displays which functions are in the file. You can either put the file itself in your home directory, or make a symbolic link to it with ‘ln -s RbasicFunctions.r target’. Now, when R starts up, it shows this:

Welcome to R!

RbasicFunctions.r was loaded, providing the following functions:

Rounding etc.:
roundup(x, numdigits=0) – correct rounding of .5 etc.
round.largest(x) – round to largest digit, i.e., 54 -> 50
ceiling.largest(x) – ceiling to largest digit, i.e., 54 -> 60
is.odd(x) – returns TRUE if roundup(x) is an odd number
is.even(x) – returns TRUE if roundup(x) is an even number

Standard errors, error bars, rmsd etc:
se(x) – standard error
rmsd(x) – root mean squared deviation

etc. and I’ve got all the functions I was missing in R. Each time I come across something else that’s missing, I just have to extend the RBasicFunctions.r file.

To leave a comment for the author, please follow the link and comment on their blog: macsci. offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...


Comments are closed.