[英]Adding and accessing package files to a new R package
I created a new project as a "R package" in RStudio v. 1.0.1.153. 我在RStudio v.1.0.1.153中创建了一个新项目作为“ R包”。 By default such a new R package project comes with file
hello.R
containing a template function 默认情况下,这样的新R包项目随附文件
hello.R
其中包含模板函数
hello <- function() {
print("Hello, world!")
}
which can be accessed simply by building and reloading the package (Ctrl+Shift+B), and then in another R session simply loading the built package and running the function: 可以通过构建并重新加载程序包(Ctrl + Shift + B)进行访问,然后在另一个R会话中,只需加载构建的程序包并运行函数即可:
> library(mylibrary)
> hello()
[1] "Hello, world!"
Now I would like to organize my functions to several files in the package. 现在,我想将我的功能组织到软件包中的几个文件中。 I add a new file
methods.R
to the .\\R\\
sub-directory of the package with another function: 我使用另一个功能将新的
methods.R
文件添加到包的.\\R\\
子目录中:
helloYouToo <- function() {
print("Hello you too!")
}
However, when I rebuild the package, and reload the library, I cannot access the function: 但是,当我重建软件包并重新加载库时,无法访问该函数:
> library(mylibrary)
> helloYouToo()
Error in helloYouToo() : could not find function "helloYouToo"
I have a couple of questions. 我有一些问题。 How should I
我该怎么办
hello.R
file) so that the files and the functions defined there are included into the package, and hello.R
文件),以便文件和在其中定义的函数包含在包中,并且 methods.R
)? methods.R
)? As @MrFlick suggested, I managed to split the functions over several files by installing devtools
and roxygen
(with dependencies). 正如@MrFlick所建议的那样,我通过安装
devtools
和roxygen
(带有依赖项)设法将功能拆分为几个文件。
After that rebuilding the package made the new functions in other files available for the users loading the package. 之后,重建软件包使其他文件中的新功能可供加载该软件包的用户使用。 However, it was necessary to restart R session in order to make updated function definitions available:
但是,必须重新启动R会话才能使更新的功能定义可用:
Restarting R session...
> library(mylibrary)
> helloYouToo()
[1] "Hello you too!"
It was even possible to to define in the package a function which uses the functions defined in two separate files: 甚至可以在包中定义一个函数,该函数使用在两个单独的文件中定义的函数:
helloDouble <- function() {
hello()
helloYouToo()
}
Resulting into 导致
Restarting R session...
> library(mylibrary)
> helloDouble()
[1] "Hello, world!"
[1] "Hello you too!"
I did not need to touch NAMESPACE file because it is as general as 我不需要触摸NAMESPACE文件,因为它与
exportPattern("^[[:alpha:]]+")
allowing all new functions which I created in the package to be available for the package user. 允许我在软件包中创建的所有新功能可供软件包用户使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.