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)?
4

1 Answer

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest