user7905871
user7905871

Reputation:

How to load all my functions in my project automatically in R

I am writing more than 6 functions and save them in my R.project. Every time, to start working using my project, I need to run each function manually one by one. Is there a way that I can load all these functions automatically?

Upvotes: 2

Views: 3962

Answers (4)

Terru_theTerror
Terru_theTerror

Reputation: 5017

You have two options:

  1. Create your own package and load it on the start-up, you will have all the function available. A tutorial

  2. Customize R start-up loading automatically your R files containing your functions. A tutorial and an example

Upvotes: 8

mishraP
mishraP

Reputation: 219

You can run the below script before starting your work:

source_code_dir <- "./R/"  #The directory where all source code files are saved.
file_path_vec <- list.files(source_code_dir, full.names = T)
for(f_path in file_path_vec){source(f_path)}

Upvotes: 0

akrun
akrun

Reputation: 887088

We can create a package in R

  1. Bundle the functions and create a package -yourpackage and then load the package

    library(yourpackage)
    
  2. One example is here

  3. Another resource is here

  4. Yet another is here

Upvotes: 1

Neal Barsch
Neal Barsch

Reputation: 2940

If you don't wish to take the package approach (which I agree is the best approach), you could stack all your functions on top of one another in an R script and source it on startup. One step instead of 6. End up with all the functions in your .GlobalEnv

Put this in an R script:

###Put in a script
eeee <- function(){
  cat("yay I'm a function")
}


ffff <- function(){
  cat("Aaaaaah a talking function")
}

If you use RStudio, the code would be as below. Otherwise change the source location. Do this in console (or in a script):

###Do this
source('~/.active-rstudio-document')

Then you can do:

eeee()
yay I'm a function

ffff()
Aaaaaah a talking function

Upvotes: 1

Related Questions