Modify the Code of an R Package

This article presents 2 ways of modifying the code of an R package

Modifying the code of an R package

Sometimes, an R package provides a great function, but we would like to modify the function just a little bit so that it does something closer to what we need. What should we do? Should we start from scratch and write our own custom function?

There is probably a better way. In this article, we show 2 ways of modifying the behavior of a function from an R package.

#1: Copy-paste the code and modify it directly

The most direct way to tweak a function is to tweak its code. To access a function code, you can:

  • Type the function name in the console without parentheses

      • ex.: lme4::lmer will print the code for the lmer() function in the lme4 package

  • Type edit(function_name), or View(function_name) in RStudio

      • ex.: edit(lme4::lmer)

  • Retrieve the code from an online repository that mirrors R CRAN. There are a few of these:

For example, we recently used the functions CDCabove() and CDCbelow() from the SSDforR package for one of our clients. These functions perform conservative dual-criterion tests for single-case and multiple-baseline designs. However, these functions include a pesky call to graphics.off(), which prevented us from generating graphs in a loop using this function (only the last graph generated was shown).

We solved this problem by copying the code of the functions into a new script file, adjusting the code by removing the graphics.off() calls, and executing these new modified functions whenever the pipeline is run. Voilà!

#2: Write a wrapper function that modifies the output

A simpler (though less direct) way of modifying the behavior of an R package is to create a wrapper function that first obtains the output of the function, then modifies the output before returning it.

For example, let's assume there is a simple function in an R package that adds 1 to a number:

add1 <- function(x) return(x+1)

If you would rather the function adds 2, you could create a new function that first executes add1(), then changes its output value and returns it:

add2 <- function(...)
{
x <- add1(...)
x <- x+1
return(x)
}

Note that this does not always work, particularly when code needs to be removed from the function (rather than added), or when an intermediary step needs to be embedded in the function. Case in point: This method would not have worked for solving the graphics.off() problem described in #1 above.

How to cite this article

To cite this article, you can use the following format:

  • D22 QuantCafé. Modify the code of an R package. Retrieved on [today's date] from https://en.d22consulting.com/quantcafe/modify-the-code-of-an-r-package