[英]R: How to run some code on load of package?
I am learning to build a package for R. Now to set it up I need to run some code when the package is being loaded via require(myPackage)
.我正在学习为 R 构建一个 package。现在要设置它,我需要在通过
require(myPackage)
加载 package 时运行一些代码。
I read the documentation on help(".onLoad")
that just made me really confused as there is no example.我阅读了有关
help(".onLoad")
的文档,这让我很困惑,因为没有示例。 How do I actually use .onLoad
?我如何实际使用
.onLoad
?
Can someone please show me a simple example?有人可以给我看一个简单的例子吗? For example I know
export(myfun)
in the NAMESPACE file will export myfun
for use, what is the code that I need to run say rnorm(10)
at package load?例如,我知道 NAMESPACE 文件中的
export(myfun)
将导出myfun
以供使用,我需要在 package 加载时运行rnorm(10)
的代码是什么?
There is usually a "processing function" (traditionally called zzz.R ) with tasks to be performed when the package is loaded, such as loading libraries and compiled code.通常有一个“处理函数”(传统上称为zzz.R ),其中包含加载包时要执行的任务,例如加载库和编译代码。 For example you can create a zzz.R file where you create this function:
例如,您可以创建一个 zzz.R 文件,在其中创建此函数:
.onLoad <- function(libname, pkgname){
x <- rnorm(10) ## dummy example
}
The R Packages ebook talks a bit more about using .onLoad()
and .onAttach()
: https://r-pkgs.org/r.html?q=onattach#when-you-do-need-side-effects R Packages 电子书更多地讨论了使用
.onLoad()
和.onAttach()
: https://r-pkgs.org/r.html?q=onattach#when-you-do-need-side-effects
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.