简体   繁体   中英

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. By default such a new R package project comes with file hello.R containing a template function

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:

> 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:

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

  1. divide the package functions into several files (not just single hello.R file) so that the files and the functions defined there are included into the package, and
  2. what is the preferred way to access also within the package such functions which are defined within the same package but in another file (like in methods.R )?

As @MrFlick suggested, I managed to split the functions over several files by installing devtools and roxygen (with dependencies).

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:

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

exportPattern("^[[:alpha:]]+")

allowing all new functions which I created in the package to be available for the package user.

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