hieko
hieko

Reputation: 393

How to automatically load a function

I have created some functions in R and whenever I need any of those functions, I need to re-create that. Please suggest me the way and steps so that i can use directly those functions in any session of R without recreating them.

Upvotes: 1

Views: 241

Answers (2)

Brandon Bertelsen
Brandon Bertelsen

Reputation: 44648

While Carl's answer is acceptable, I personally think that this is exactly the situation where you should package your functions and simply call them as a library.

There are very good reasons to do this:

  • Documentation (with emphasis!)
  • Tests
  • Easy loading (library(mypackage))
  • Easy to share and portable across systems
  • Easy to use within reporting (Rmd/knitr)
  • Reduces potential for duplication
  • Learning the R package system will be a strong part of your toolbox and other benefits of organizing your code appropriately will become apparent.

Upvotes: 3

Carl Boneri
Carl Boneri

Reputation: 2722

I have a series of functions that I need across all sessions. The trick is to add them to your .First file so that they are sourced into every session globally.

A helper function to find your first-file

find.first <- function(edit = FALSE, show_lib = TRUE){

  candidates <- c(Sys.getenv("R_PROFILE"),
                  file.path(Sys.getenv("R_HOME"), "etc", "Rprofile.site"),
                  Sys.getenv("R_PROFILE_USER"),
                  file.path(getwd(), ".Rprofile")
                  )

  first_hit <- Filter(file.exists, candidates)

  if(show_lib & !edit){
    return(first_hit)
  }else {
    file.edit(first_hit)
  }
}

Say your scripts you use everywhere are in '/mystuff/R'

# Pop open the first Rprofile file.
find.first(edit = TRUE)

You will see something like this:

##Emacs please make this -*- R -*-
## empty Rprofile.site for R on Debian
##
## Copyright (C) 2008 Dirk Eddelbuettel and GPL'ed
##
## see help(Startup) for documentation on ~/.Rprofile and Rprofile.site

# ## Example of .Rprofile
# options(width=65, digits=5)
# options(show.signif.stars=FALSE)
# setHook(packageEvent("grDevices", "onLoad"),
#         function(...) grDevices::ps.options(horizontal=FALSE))
# set.seed(1234)
#.First <- function(){}
#
#

Edit the function to something like:

.First <- function(){
  all_my_r <- list.files('/mystuff/R', full.names = T,
                         recursive = T, pattern = ".R$" )
    lapply(all_my_r, function(i){
     tryCatch(source(i), error = function(e)NULL)
    })

}

Save the file. Then restart the session.

Upvotes: 0

Related Questions