Last updated: 2024-02-09

Checks: 7 0

Knit directory: bioinformatics_tips/

This reproducible R Markdown analysis was created with workflowr (version 1.7.1). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20200503) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version a62ef5d. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rproj.user/

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/testing.Rmd) and HTML (docs/testing.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd a62ef5d Dave Tang 2024-02-09 tryCatch and withCallingHandlers examples
html 674c18c Dave Tang 2024-02-09 Build site.
Rmd 245b9f3 Dave Tang 2024-02-09 Error handling in R and Python
html 72336b6 Dave Tang 2022-12-07 Build site.
Rmd 7ab5011 Dave Tang 2022-12-07 Implement testing

You should always include tests in your scripts, programs, and workflows. Carefully implemented tests can help identify problems before they propagate downstream into other analyses.

Two types of tests include:

  1. Inside-out or unit testing – include tests inside your script/program
  2. Outside-in or integration testing – write tests that run your script/program (this can be automated using CI/CD)

In essence, tests verify whether something returns an expected value or result and that’s it. In Python we can add assertions (in Ruby there is the Test::Unit::Assertions module), which is a simply an expression that is supposed to be true at a particular point in a program.

Broadly speaking, assertions fall into three categories:

  1. A pre-condition is something that must be true at the start of a function in order for it to work correctly.
  2. A post-condition is something that the function guarantees is true when it finishes.
  3. An invariant is something that is always true at a particular point inside a piece of code.

Assertions are not just about catching errors but they also help people understand programs. Each assertion gives the person reading the program a change to check that their understanding matches what the code is doing.

Two general rules to follow when adding assertions include:

  1. Fail early, fail often - the greater the distance between when and where an error occurred and when it is noticed, the harder the error will be to debug, so good code catches mistakes as early as possible.
  2. Turn bugs into assertions or tests - whenever you fix a bug, write an assertion that catches the mistake should you make it again. If you made a mistake in a piece of code, the odds are good that you have made other mistakes nearby, or will make the same mistake (or a related one) the next time you change it.

In summary, program defensively, i.e. assume that errors are going to arise, and write code to detect them when they do. Put assertions in programs to check their state as they run, and to help readers understand how those programs are supposed to work. Use pre-conditions to check that the inputs to a function are safe to use and use post-conditions to check that the output from a function is safe to use.

An interesting idea is to write tests before writing code in order to help determine exactly what that code is supposed to do. This is known as Test-Driven Development and advocates writing tests before writing the code.

R

Three signalling conditions in R:

  1. Errors: execution must stop
  2. Warnings: partial recovery
  3. Messages:
stop("This is what an error looks like")
Error in eval(expr, envir, enclos): This is what an error looks like
warning("This is what a warning looks like")
Warning: This is what a warning looks like
message("This is what a message looks like")
This is what a message looks like

In base R, errors are signalled, or thrown, by stop(); call. = FALSE is used because it’s not typically useful to include the call.

h <- function() stop("This is an error!", call. = FALSE)
h()
Error: This is an error!

The {rlang} equivalent is abort.

library(rlang)
h <- function() abort("This is an error!")
h()
Error in `h()`:
! This is an error!

The best error messages tell you what is wrong and point you in the right direction to fix the problem. The {tidyverse} style guide discusses a few general principles that may be useful.

Warnings, signalled by warning(), are weaker than errors: they signal that something has gone wrong, but the code has been able to recover and continue. Unlike errors, you can have multiple warnings from a single function call:

Warnings occupy a somewhat challenging place between messages (“you should know about this”) and errors (“you must fix this!”), and it’s hard to give precise advice on when to use them. Generally, be restrained, as warnings are easy to miss if there’s a lot of other output, and you don’t want your function to recover too easily from clearly invalid input.

Messages, signalled by message(), are informational; use them to tell the user that you’ve done something on their behalf. Good messages are a balancing act: you want to provide just enough information so the user knows what’s going on, but not so much that they’re overwhelmed.

The purposes of cat() and message() are different. Use cat() when the primary role of the function is to print to the console, like print() or str() methods. Use message() as a side-channel to print to the console when the primary purpose of the function is something else. In other words, cat() is for when the user asks for something to be printed and message() is for when the developer elects to print something.

The simplest way of handling conditions in R is to simply ignore them:

f2 <- function(x) {
  try(log(x))
  10
}
f2("a")
Error in log(x) : non-numeric argument to mathematical function
[1] 10

Two functions, tryCatch() and withCallingHandlers(), allow us to register handlers, functions that take the signalled condition as their single argument. They differ in the type of handlers that they create:

tryCatch(
  error = function(cnd) {
    # code to run when error is thrown
  },
  code_to_run_while_handlers_are_active
)

withCallingHandlers(
  warning = function(cnd) {
    # code to run when warning is signalled
  },
  message = function(cnd) {
    # code to run when message is signalled
  },
  code_to_run_while_handlers_are_active
)

tryCatch() registers exiting handlers, and is typically used to handle error conditions. It allows you to override the default error behaviour. For example, the following code will return NA instead of throwing an error:

f3 <- function(x) {
  tryCatch(
    error = function(cnd) NA,
    log(x)
  )
}

f3("x")
[1] NA
f3(7.389056)
[1] 2

The stop() function is never run because once a condition is caught, it exits.

tryCatch(
  message = function(cnd) "There",
  {
    message("Here")
    stop("This code is never run!")
  }
)
[1] "There"

Add a finally argument to have code that always runs.

tryCatch(
  message = function(cnd) "There",
  {
    message("Here")
    stop("This code is never run!")
  },
  finally = {
    message("This always runs!")
  }
)
This always runs!
[1] "There"

withCallingHandlers sets up calling handlers: code execution continues normally once the handler returns.

tryCatch(
  message = function(cnd) cat("Caught a message!\n"), 
  {
    message("Someone there?")
    message("Why, yes!")
  }
)
Caught a message!
withCallingHandlers(
  message = function(cnd) cat("Caught a message!\n"), 
  {
    message("Someone there?")
    message("Why, yes!")
  }
)
Caught a message!
Someone there?
Caught a message!
Why, yes!

Python

In Python when an error occurs, an exception is automatically triggered and the default way to handle it is to stop the program and output an error message. Exceptions can also be manually triggered using raise. You can catch exceptions and handle them as you like using:

Use assert to conditionally trigger an exception; check if something is true.

Exceptions are typically used for a variety of purposes.


sessionInfo()
R version 4.3.2 (2023-10-31)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 22.04.3 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 
LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.20.so;  LAPACK version 3.10.0

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

time zone: Etc/UTC
tzcode source: system (glibc)

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] rlang_1.1.1     workflowr_1.7.1

loaded via a namespace (and not attached):
 [1] vctrs_0.6.4       httr_1.4.7        cli_3.6.1         knitr_1.44       
 [5] xfun_0.40         stringi_1.7.12    processx_3.8.2    promises_1.2.1   
 [9] jsonlite_1.8.7    glue_1.6.2        rprojroot_2.0.3   git2r_0.32.0     
[13] htmltools_0.5.6.1 httpuv_1.6.12     ps_1.7.5          sass_0.4.7       
[17] fansi_1.0.5       rmarkdown_2.25    jquerylib_0.1.4   tibble_3.2.1     
[21] evaluate_0.22     fastmap_1.1.1     yaml_2.3.7        lifecycle_1.0.3  
[25] whisker_0.4.1     stringr_1.5.0     compiler_4.3.2    fs_1.6.3         
[29] pkgconfig_2.0.3   Rcpp_1.0.11       rstudioapi_0.15.0 later_1.3.1      
[33] digest_0.6.33     R6_2.5.1          utf8_1.2.4        pillar_1.9.0     
[37] callr_3.7.3       magrittr_2.0.3    bslib_0.5.1       tools_4.3.2      
[41] cachem_1.0.8      getPass_0.2-2