Overview

This comprehensive guide walks you through transforming reusable R functions into a professional-grade package, sharing it on GitHub, and maintaining it long-term. The process is organized into three phases:

  1. Creating the package locally
  2. Publishing to GitHub
  3. Updating and maintaining the package

Prerequisites

Before beginning, ensure you have:

  • R and RStudio installed
  • The devtools and usethis packages: install.packages(c("devtools", "usethis"))
  • A GitHub account
  • Git installed and configured on your machine
  • (Recommended) The roxygen2 package: install.packages("roxygen2")

Phase 1: Create the Package Locally

Step 1: Initialize the Package

package_name <- "aucmat"
pack_path <- file.path("C:/Users/tralucck/OneDrive/", package_name)
your_name <- "Lucas VHH Tran"

# Create the package structure
usethis::create_package(pack_path)

This creates a new directory with the essential structure of an R package. Open the newly created .Rproj file in RStudio immediately.

Step 2: Preflight Checks and Setup

# Install required packages if needed
needs <- c("usethis", "devtools", "roxygen2", "testthat", "pkgdown", 
           "gitcreds", "git2r", "gert", "here")
to_install <- setdiff(needs, rownames(installed.packages()))
if (length(to_install)) install.packages(to_install)

# Check if Git is available
ok_git <- tryCatch({ nzchar(Sys.which("git")) }, error = function(e) FALSE)
if (!ok_git) message("Git not found on PATH. Install from https://git-scm.com/ and restart R.")

# Set up GitHub Personal Access Token if not already done
if (is.na(Sys.getenv("GITHUB_PAT", unset = NA))) {
  message("No GITHUB_PAT detected. Creating one...")
  usethis::create_github_token()
  gitcreds::set_github_pat()
}

# Configure Git
usethis::use_git_config(user.name = your_name, user.email = "tranhungydhcm@gmail.com")

Step 3: Add a License

usethis::use_mit_license(your_name)

Step 4: Write Your Functions and Documentation

# Create R files for your functions
list_of_functions <- c("utils", "plot_roc_with_combos", 
                       "generate_data_analytical", "tableroc")

for (func in list_of_functions) {
  usethis::use_r(func) 
}

Example function in R/utils.R:

#' Calculate AUC from ROC data
#'
#' @param sensitivity Numeric vector of sensitivity values
#' @param specificity Numeric vector of specificity values
#' @return Numeric value representing AUC
#' @examples
#' # Calculate AUC for example data
#' sens <- c(0, 0.5, 1)
#' spec <- c(1, 0.5, 0)
#' calculate_auc(sens, spec)
#' @export
calculate_auc <- function(sensitivity, specificity) {
  # Implementation here
  1 - sum(diff(1 - specificity) * sensitivity[-1])
}

Step 5: Create a Compelling README

usethis::use_readme_md()

Edit the README.md file to include:

  1. A brief description of your package
  2. Installation instructions
  3. Basic usage examples
  4. Any other relevant information

Step 6: Edit the DESCRIPTION File

Edit the DESCRIPTION file to include accurate metadata:

Package: aucmat
Title: A Toolbox for Biomarkers Data Analysis
Version: 0.0.0.9000
Date: 2025-09-18
Authors@R: 
    person("Lucas", "VHH Tran", email = "tranhungydhcm@gmail.com", role = c("aut", "cre"))
Description: This package provides functions to download, process, and analyze biomarkers data with a focus on ROC analysis and visualization.
License: MIT + file LICENSE
URL: https://github.com/vanhungtran/aucmat
BugReports: https://github.com/vanhungtran/aucmat/issues
Depends:
    R (>= 4.0.0)
Imports:
    dplyr,
    ggplot2,
    BiocManager,
    GEOquery
Suggests:
    knitr,
    rmarkdown,
    testthat (>= 3.0.0)
Config/testthat/edition: 3
VignetteBuilder: knitr

Step 7: Add Tests and a Vignette

usethis::use_testthat() # Enable testing infrastructure
usethis::use_test("utils") # Create test file for utils functions

# For a long-form tutorial vignette
usethis::use_vignette("introduction-to-aucmat")

Example test in tests/testthat/test-utils.R:

test_that("calculate_auc works correctly", {
  sens <- c(0, 0.5, 1)
  spec <- c(1, 0.5, 0)
  expect_equal(calculate_auc(sens, spec), 0.75)
})

Step 8: Build, Check, and Install Locally

usethis::use_roxygen_md() # Enable markdown in roxygen comments
devtools::document() # Generate NAMESPACE & man/ from roxygen

devtools::install() # Build & install in your R library
devtools::check() # Run R CMD check

Phase 2: Publish to GitHub

Step 1: Connect to GitHub Repository

usethis::use_git() # Initialize a local git repo
usethis::use_github() # Create repo on GitHub and set remote 'origin'

Step 2: Commit and Push to GitHub

# Clean up any stale man pages
unlink("man", recursive = TRUE)
dir.create("man")

# Regenerate documentation
devtools::document()

# Run tests
devtools::test()

# Full check
devtools::check()

# Commit and push
gert::git_add(".")
gert::git_commit("Initial commit: aucmat package")
gert::git_push()

Phase 3: Update the Package

The development cycle consists of:

  1. Make Changes: Add new functions, fix bugs, improve documentation
  2. Increment Version: Update the version number in DESCRIPTION
  3. Re-document: Run devtools::document() after changing roxygen2 comments
  4. Test: Run devtools::test() to ensure nothing is broken
  5. Check: Run devtools::check() to ensure package health
  6. Commit and Push: Use Git to commit changes and push to GitHub

Additional Useful Steps

# Package website
usethis::use_pkgdown() # Add pkgdown config
pkgdown::build_site() # Build docs site in docs/
usethis::use_github_pages() # Publish via GitHub Pages

# Continuous integration
usethis::use_github_action_check_standard() # Set up CI

# Ignore unnecessary files
usethis::use_build_ignore(c("doc", "docs", "README_files"))

Summary: Key Files & Their Purposes

File Purpose Pro Tip
DESCRIPTION Metadata: name, version, author, description, dependencies Be precise. List all Imports. Use Authors@R with ORCID
README.md The front page of your GitHub repository Include a clear, compelling example that works
LICENSE Legal terms for sharing your code Never leave this blank. use_mit_license() is a safe default
NAMESPACE (Auto-generated) Lists exported and imported functions Manage with @export and @importFrom roxygen2 tags
man/*.Rd (Auto-generated) Function help files Write clear roxygen2 comments with @param and @return

Common Fixes

  • Not connected to GitHub or PAT errors:
usethis::create_github_token()
gitcreds::set_github_pat()
usethis::use_github()
  • Missing NAMESPACE/man pages: run devtools::document()
  • Imports not found: add use_package("pkg") and @importFrom pkg fun, then document()
  • Check failures: read devtools::check() output, fix issues, and re-run

Quickstart Function

quickstart <- function(pkg_path = "C:/Users/tralucck/OneDrive/aucmat",
                       pkg_title = "AUC Matrix Analysis",
                       author = "Lucas VHH Tran",
                       github_repo = NULL) {
  # Create package
  usethis::create_package(pkg_path)
  
  # Set up basics
  usethis::use_mit_license(author)
  usethis::use_readme_md()
  usethis::use_testthat()
  usethis::use_vignette("introduction")
  
  # Configure Git and GitHub
  usethis::use_git_config(user.name = author, user.email = "tranhungydhcm@gmail.com")
  if (!is.null(github_repo)) {
    usethis::use_github(repo = github_repo)
  }
  
  message("Package ", basename(pkg_path), " created successfully!")
}

Conclusion

This guide provides a comprehensive workflow for creating, publishing, and maintaining R packages. By following these steps, you can transform your R code into professional, shareable packages that follow best practices for documentation, testing, and distribution.

Remember that package development is iterative—start simple and gradually add complexity as needed. The R package ecosystem provides excellent tools to support this process, making it easier than ever to create high-quality, reusable code. ```

I’ve updated the guide to move the “Create a Compelling README” step before the “Edit the DESCRIPTION File” step as requested. The steps are now in this order:

  1. Initialize the Package
  2. Preflight Checks and Setup
  3. Add a License
  4. Write Your Functions and Documentation
  5. Create a Compelling README
  6. Edit the DESCRIPTION File
  7. Add Tests and a Vignette
  8. Build, Check, and Install Locally