2026
Prepare a simple R package for distributing documented functions
Explain the terms Repository, Dependency, and Namespace
Implement testing in an R package
Collaboratively work on an R package on GitHub
What is an R package?
shareable collection of documented code and/or dataWhat is a repository?
git version control and stored in GitHubWhat is a dependency?
Any external thing your package relies on to work (most commonly, another package).
With usethis, we add dependencies like this:
We should try to avoid dependencies as much as we can (within reason), because:
What is a namespace?
library("your_package")NAMESPACE file:What is a namespace?
library("your_package")NAMESPACE file:@importFrom package function and @import package (we did this in function 5).DESCRIPTION fileMaking custom data available to the user of the package
#' Create a string of random DNA
#'
#' @param DNA_length length of the randomly created DNA
#'
#' @returns a string of random DNA
#' @export
random_DNA <- function(DNA_length){
DNA_vec <- sample(c("A", "T", "G", "C"), size = DNA_length, replace = TRUE)
DNA_str <- paste0(DNA_vec, collapse = "")
return(DNA_str)
}Those comments on top of the function is how an R package makes its documentation show up when running ?function_name in the Console.
devtools::document() converts those comments into .Rd files in the man folder of the package using roxygen2. Otherwise you would have to write them yourself…
The purpose of testing:
With testhat, we have a collection of expect_* functions that check for specific conditions
test_that("rnadom DNA has the correct length", {
DNA_length <- 100
generated_DNA <- random_DNA(DNA_length)
expect_equal(nchar(generated_DNA), DNA_length)
})
test_that("all letters are valid DNA", {
DNA_letters <- c("A", "C", "T", "G")
generated_DNA <- random_DNA(400)
generated_DNA <- strsplit(generated_DNA, "")[[1]] # transform to vector form
is_valid_letter <- generated_DNA %in% DNA_letters
expect_true(all(is_valid_letter))
})Solution: Delete NAMESPACE file and rerun devtools::document()
Solution: Fix merge conflicts
devtools::check()❯ checking examples ... ERROR
Running examples in ‘cdogma-Ex.R’ failed
The error most likely occurred in:
> base::assign(".ptime", proc.time(), pos = "CheckExEnv")
> ### Name: hello
> ### Title: Hello, World!
> ### Aliases: hello
>
> ### ** Examples
>
> hello()
Error in hello() : could not find function "hello"
Execution halteddevtools::check()❯ checking examples ... ERROR
Running examples in ‘cdogma-Ex.R’ failed
The error most likely occurred in:
> base::assign(".ptime", proc.time(), pos = "CheckExEnv")
> ### Name: hello
> ### Title: Hello, World!
> ### Aliases: hello
>
> ### ** Examples
>
> hello()
Error in hello() : could not find function "hello"
Execution haltedSolution: Delete R/hello.R and man/hello.md
© 2023-2026 Leon Eyrich Jessen · All rights reserved · R for Bio Data Science