Monday, July 22, 2013

Loading up your custom toolkits at startup - R

If you are anything like me then you have dozens if not hundreds of personal functions that you have written to accomplish a number of tasks.  Many of the tasks that you would like to do are similar to previous tasks that you have already done.  So how are you going to bridge the functions across your disjoint projects?

There are a four good options I see which might fit different projects:

1. You copy and paste your old code at the beginning of your new code so that when you run the code the previously designed functions are available.  Pros: simple, Cons: makes your code a lot longer than you may prefer.

2. You create a package or the skeleton of the package and load your functions into it as you write them. When you write new code that uses those functions you just load your package. Pros: this creates very clean code, Cons: this can be a little complicated and your code might not be at a level of refinement that would warrant packaging up your code and then potentially having to make revisions on it and updating the package frequently.

3. You could source your code with the "source" function.  Pros: this allows your code to be nearly as clean as loading your code as its own package and it allows you to easily update your source file as frequently you may want.  Cons: Nothing obvious.

4. Set up start-up profiles with R so that you can customize your programming environment easily.  This solution is kind of the point of this post however it is not clear to me that this is the best option.  However, this is what I have done.  I used Quick-R: Customizing Startup article as a reference.

In the .Rprofile file which I found in "C:/users/user_name/Documents":

.First <- function(){
  # Load up functions that I always want to be available.
  source("C:/Dropbox/R-Startup-Profiles/Base.R")
 
  # Optionally load up toolkit profiles for each R programming paradigm. 
  print("Profiles Available: Shiny, Sim, Concerto")
  Shiny <<- function() source("C:/Dropbox/R-Startup-Profiles/Caller.R")
  Sim <<- function() source("C:/Dropbox/R-Startup-Profiles/Simulation.R")
  Concerto <<- function() source("C:/Dropbox/R-Startup-Profiles/Concerto.R")
}

Formatted by Pretty R at inside-R.org


So now every time R startups it will load my always needed functions which are stored in the Base.R file.  Then I will choose which environment I want to program in.  If for instance I want to program a Shiny app then I would just send the command:
>Shiny()
and that will load my Shiny profile which is pretty simple:

cat("Loading Shiny!")
library(shiny)
library(shinyIncubator)
setwd("c:/dropbox/shiny_r/")

Formatted by Pretty R at inside-R.org

No comments :

Post a Comment