As artificial intelligence (AI) and large language models (LLMs) become increasingly important tools for facilitating both trivial and non-trivial tasks that require thought and reasoning, it would be reckless to completely ignore the availability of excellent digital assistants both in a professional capacity and at home for hobby projects.

However, to err is human, and since these AI tools were developed by humans, they have a propensity for making mistakes, displaying sycophantic tendencies, doing what they were not requested to do etc. In this regard, it is crucial to formulate good prompts and to explain to the machine precisely what needs to be done.

R is a programming language with a vast ecosystem of packages for various tasks, ranging from estimating hydrological models to the spectral analysis of signals. It outclasses Stata in data transformation owing to its ability to handle multiple data sets simultaneously and to inspect various objects simply by entering their names in the console (cough cough matrix list mymat). It crushes EViews because it can handle local and global variables, which is fundamental to programming. It is developed by statisticians for statisticians, unlike Python, which is written by computer scientists for everyone (which renders it a jack-of-all-trades, master of none). And since it boasts a long catalogue of packages, it is inevitable that some of those packages fall short of users’ expectations, run slowly, do not print the results in a convenient manner, or harbour mathematical and programming errors.

Luckily, there is hope. LLMs such as OpenAI ChatGPT and Anthropic Claude have been trained on a huge sample of publicly available codes, and they reason pretty well about programming logic. As a result, they can be used to hallucinate R code, debug it, test it, and improve it. Since the tasks of an R package maintainer are different from those of a regular user, I have compiled several frequently used prompts that I feed into these two LLMs to automate tasks that would tedious or error-prone due to the limited attention span and memory capacity of a human. It goes without saying that every single bit of machine-hallucinated output must be scrutinised by a competent human. No single change should be accepted merely because it was proposed by a machine. Always, always review AI-generated suggestions and reject them if they are irrelevant, erroneous, verbose, or unmaintainable.

Since every modification is potentially destructive, always back up your entire codebase before granting your favourite LLM access to modify / write files!

With these caveats in mind, here are 10 tips for those wishing to spend less time doing menial tasks related to R package development and maintenance.

  1. (To add after requesting a new feature.) After implementing each new feature, (1) integrate it with existing functions, (2) assess if modularisation is possible, and (3) try to reduce the amount of code as much as possible, without compromising functionality, readability or maintainability.
  2. Ensure unit-test coverage >95%, but write as few new tests as possible that provide as much coverage as possible. Vary several arguments simultaneously to exercise as many code branches as possible in single call. Attempt to modify existing tests and function calls to traverse previously unexplored execution paths in as few calls as possible, and only if it is insufficient, add new function calls with combinations of arguments chosen to execute previously untested lines. Importantly, avoid writing tests that re-implement the definition verbatim. Do not re-calculate objects from first principles and try to match them with the results of internal calculations based on the same definitions -- instead, prioritise unit tests that establish desirable numerical properties, convergence, speed, parsimony, or that ensure certain theoretically necessary relationships between various returned objects. Retain the tests that are not very useful programmatically (or contribute little to measured code coverage) but that ensure robustness, stability, and comparability.
  3. Here are the timings for the package’s unit tests:
    a <- devtools::test()
    seconds <- sapply(a, "[[", "real")
    file <- sapply(a, "[[", "file")
    aggregate(seconds ~ file, FUN = sum)  # Output this

    You see, the execution times are excessive. Review the tests critically. You are checking the tiniest inconsequential things. Speed them up by optimising numerically intensive parts. Locate expensive function calls. Reduce the sizes of simulated sample sizes if applicable. Experiment with several random seeds (e.g. integers between 1 and 10) to find the one that yields the fastest execution times and rapid convergence. Once you identify a good combination, try reusing the resulting estimated object in as many tests as possible without re-estimation. It should be easy for you to find slow calls. At the end, do not re-run all tests or all checks because obviously you will be executing the relevant tests and examining test objects during this job! Save tokens and my CPU time. Be economical. And optimise both tests and examples in the documentation for speed!

  4. The number of unit tests is huge and probably does not justify the goal; some of them are literally checking the definitions against identically reproduced definitions, which will cause a failure after those implementations are revised. This is silly. Too many tests! Assess which of them are not contributing to code coverage or the verification of important mathematical, numerical or functional properties. Run test coverage, examine the report, identify which statements were not executed at all, and which were evaluated repeateedly. In future, do not write too many checks; check only the aspects that may fail in real-life scenarios; do not copy-paste internal calculations and check if the outputs are tautologically equal: of course they are! Drop redundant tests that do not improve unit-test coverage and do not provide assurances regarding the correctness or the robustness of the implementation. Try altering several arguments simultaneously to cover as many branches and unique lines as possible. I want as few tests as possible with as much coverage as possible, and maybe several carefully considered tests than stablish the stability and reliability of the algorithms. Nothing else! Here is the coverage report and the frequency of line evaluations:
    a <- covr::package_coverage()
    write.csv(a, "coverage.csv")
    writeLines(covr::annotate_coverage(a, context = Inf, max_lines = Inf), "coverage.txt")  # Output this!

    In the future, write as few unit tests as possible to cover the maximum amount of code.

  5. Time the heaviest numerical routines, save the evaluation times as a list element or as an attribute. Record the time spent on optimisation, simulation, root-finding, integration, estimation etc. Use simple features (Sys.time()) and timer initialistions like tic0 <- Sys.time() before and another Sys.time() and difftime after. When requested, report the execution times in summaries on a separate line (in seconds, 3 decimal places). The summary objects should preserve the recorded execution times.
  6. Okay. Time the step back and retrace. There are two problems. The amount of code is exploding with each new feature. Check the code for redundancies, superfluous calculations, unjustified expensive checks. It needs to be sped up, streamlined, and modularised. Profile the principal functions. Scrutinise the profiling information and check which functions are invoked most frequently. Profile what's slow in numerical routines. Profile what's slow in methods. Try speeding it up. From now on, when you scan code and see a bug, describe it in your response and ask whether it should be fixed. And make sure that you do not sacrifice existing functionality in these simplifications!
  7. Ensure that all \eqns and \deqns in the documentation include a plain-text alternative as the second argument.
  8. Check consistency between functions and their documentation (which might be lagging behind the developments). Focus on signatures, arguments and their defaults, returned-object structures, mathematical descriptions and included examples.
  9. Check if it is possible to eliminate the number of package dependencies without sacrificing functionality, efficiency, or reliability. Determine if some imported packages are redundant or are providing simple functions that can be copied and pasted into my package. If so, copy them with proper attribution (documenting their provenance as a comment with one-line licence information) tp get rid of the external dependency.
  10. My package seems to be slow. Is there overhead? Does it make sense to rewrite certain functions using Rcpp? If yes, try relegating the numerically heavy operations to Rcpp; do not hesitate to make use of excellent fast libraries such as RcppArmadillo or similar. Benchmark the compiled code against the original R implementation. Report the timings. Let me make a decision.

After implementing the AI-suggested changes, finally, do the following five things:

  • Check the release with todor::todor_package() to make sure that no TODOs are left behind;
  • Calculate the code coverage with covr::package_coverage() and write unit test for the lines that were never run in tests and examples;
  • Lint the package with lintr::lint_package() (feel free to increase the line-length limit to 120, or to disable indentation checks, or to allow more naming conventions etc.);
  • Perform library(goodpractice); gp(checks = all_checks()[!grepl("^lintr|^covr", all_checks())]) (we have already checked coverage and linted the package) to check function complexity, get tips on organising DESCRIPTION, inherited parameters, naming files and general book-keeping;
  • In the terminal, run R CMD check --as-cran to verify strict compliance with the established package-writing rules.

I sincerely hope that this to-do list helps eliminate at least some of the 33-year-old technical debt and iron out the kinks in R packages.

All of these tips and prompts are a culmination of 5 years of hands-on R package development. I did not use AI to come up with these ideas; I use these ideas to exchange with AI.

OpenAI ChatGPT Codex for R package development in action