Customizing R: startup script
[This article was first published on macsci, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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.Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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(“—————\n\n”,sep=””)
if(file.exists(“~/RbasicFunctions.r”)){
source(“~/RbasicFunctions.r”)
cat(“RbasicFunctions.r was loaded, providing the following functions:\n\n”,sep=””)
print.functions()
}
}
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.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.