Reputation: 393
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
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:
library(mypackage)
)Upvotes: 3
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