R 如何自动加载函数

R 如何自动加载函数,r,R,我已经在R中创建了一些函数,每当我需要这些函数中的任何一个时,我都需要重新创建它。请告诉我方法和步骤,以便我可以在R的任何会话中直接使用这些函数,而无需重新创建它们 我在所有会话中都有一系列需要的函数。诀窍是将它们添加到.First文件中,以便在每个会话中全局地获取它们 用于查找第一个文件的辅助函数 find.first <- function(edit = FALSE, show_lib = TRUE){ candidates <- c(Sys.getenv("R_PROFI

我已经在R中创建了一些函数,每当我需要这些函数中的任何一个时,我都需要重新创建它。请告诉我方法和步骤,以便我可以在R的任何会话中直接使用这些函数,而无需重新创建它们

我在所有会话中都有一系列需要的函数。诀窍是将它们添加到.First文件中,以便在每个会话中全局地获取它们

用于查找第一个文件的辅助函数

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)
  }
}
您将看到如下内容:

##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(){}
#
#
##Emacs请制作此-*-R-*-
##Debian上R的Rprofile.site为空
##
##版权所有(C)2008 Dirk Eddelbuettel和GPL'ed
##
##有关~/.Rprofile和Rprofile.site上的文档,请参阅帮助(启动)
###.Rprofile的示例
#选项(宽度=65,数字=5)
#选项(show.signif.stars=FALSE)
#setHook(packageEvent(“grDevices”、“onLoad”),
#函数(…)grDevices::ps.options(水平=假))
#种子集(1234)

#首先虽然卡尔的回答是可以接受的,但我个人认为这正是你应该打包你的函数并简单地将它们称为库的情况

这样做有很好的理由:

  • 文档(强调!)
  • 测验
  • 轻松加载(
    库(mypackage)
  • 易于跨系统共享和移植
  • 易于在报告中使用(Rmd/knitr)
  • 减少重复的可能性
  • 学习R包系统将是工具箱的重要组成部分,适当组织代码的其他好处将变得显而易见

您是否使用source()?资料来源()如果路径正确,则加载函数。您每次重新创建它们是什么意思?#joel.wilson:我需要该功能在当前登录R会话时可用,我需要使用该特定函数,我需要再次执行该函数定义的脚本,然后才能使用该功能。我需要一种在R会话中包含该函数的方法,这样我就不必每次都创建它了。哦……如果不是很明显,请取消对#的注释。首先,我强烈支持这条消息。
##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(){}
#
#
.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)
    })

}