简体   繁体   中英

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?

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

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

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

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)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM