03 - Package Skeleton

The reference for this vignette is Wickham et al. (2024).

Loading the Required R Packages

This vignette and the next use the following R packages:

library(cpp4r)
library(devtools)
library(bench)
library(usethis)

Creating a Dummy Package

You can create a new package in RStudio (or VSCode) by running:

pkg_template("~/github/cpp4r/cpp4rexamples")

This command will create a new folder containing the cpp4rexamples package. Afterward, you can run use_cpp4r() to add the necessary code to the package.

Number’s Sign

A more complex function is one that returns the sign of a number:

[[cpp4r::register]] int sign_cpp(double x) {
  if (x > 0) {
    return 1;
  } else if (x == 0) {
    return 0;
  } else {
    return -1;
  }
}

Add this function to a new file src/03_sign.h.

Here is the R version of the function:

sign_r <- function(x) {
  if (x > 0) {
    1
  } else if (x == 0) {
    0
  } else {
    -1
  }
}

Do not forget to include the new header file in main.cpp.

Document both functions and compare their outputs.

Installing the Package

To document and install the package as an R library, you can run the following functions:

cpp4r::register()
devtools::document()
devtools::install()

Afterward, you can access the functions by loading the package with library(cpp4rexamples).

Each time you need to make changes to the C++ code, you can run load_all() again to test and then reinstall the package.

Good Practice

It is good practice to include a license for your code. For example, you can use the Apache license by running:

usethis::use_apache_license()

Additionally, it is recommended to use use_build_ignore() to ignore files that are unnecessary for package installation. For example, to ignore the docs folder, you can run:

usethis::use_build_ignore("docs")

Your .Rbuildignore file can include the following lines, which you can edit manually to exclude specific files and directories:

^\.vscode$
^LICENSE\.md$
^cpp4rexamples\.Rproj$

References

Wickham, Hadley, Jenny Bryan, Malcolm Barrett, and Andy Teucher. 2024. “Automate Package and Project Setup.” https://usethis.r-lib.org/.

Loading...