When creating an R package, documentation is an important aspect to ensure that the package is well-documented, easy to understand, and can be used by other developers. The roxygen2 package is a popular tool for creating documentation in R packages. It allows users to write documentation alongside the code itself using special syntax.
To use the roxygen2 package, we first need to install it using the following command:
install.packages("roxygen2")
Next, we need to use special syntax to write documentation alongside our R code. For example, to add a function documentation, we would write a comment block immediately preceding the function code, like this:
#' Function title
#'
#' Function description goes here.
#'
#' @param arg1 Description of arg1
#' @param arg2 Description of arg2
#' @return Description of the output
#' @examples
#' function_example()
#' @export
function_name <- function(arg1, arg2) {
# function code goes here
}
In the comment block, we use the #’ notation to indicate that we are writing documentation. The first line is the title of the function, followed by a brief description of the function’s purpose. We then use the @param notation to document each argument of the function, and the @return notation to describe the output of the function.
The @examples notation is used to provide examples of how to use the function. These examples will be run automatically when building the package to ensure that the function is working as expected.
Finally, we use the @export notation to indicate that the function should be exported from the package and made available to other packages and users.
Once we have written our documentation, we can use the roxygen2 package to automatically generate the package documentation files using the following command:
roxygen2::roxygenise()
This will create a man directory in our package directory, containing the HTML files with the function documentation.
In summary, the roxygen2 package is a powerful tool for creating documentation in R packages. It allows us to write documentation alongside our code using special syntax, and automatically generates the package documentation files.