简体   繁体   English

如何在R中自动将所有功能加载到项目中

[英]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. 我编写了6个以上的函数,并将它们保存在我的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. 自定义R启动,自动加载包含功能的R文件。 A tutorial and an example 教程示例

We can create a package in R 我们可以在R创建一个包

  1. Bundle the functions and create a package - yourpackage and then load the package 捆绑功能并创建一个包yourpackage ,然后加载该包

     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. 如果您不希望采用包方法(我同意这是最好的方法),则可以将所有函数彼此堆叠在R脚本中,并在启动时将其作为源。 One step instead of 6. End up with all the functions in your .GlobalEnv 一步代替6。最后完成.GlobalEnv中的所有功能

Put this in an R script: 将其放在R脚本中:

###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. 如果使用RStudio,代码将如下所示。 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)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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