Help for when things don’t turn out how you expect.
Time: 50 min
Description: This session will provide you with advice and skills on how to start tackling error messages and where to look for help.
Errors messages are common when coding and are a way the computer communicates it doesn’t understand what the instructions it has been given are.
Figure 1: https://xkcd.com/1739/
Some general good advice can be found in https://adv-r.hadley.nz/debugging.html with some specific tips and tricks for R.
Finding your bug is a process of confirming the many things that you believe are true — until you find one which is not true. —Norm Matloff
Rubber Duck debugging
My general process focuses on the initial source of the error and then starts to work backwards in command history.
Lets look at a few common R errors so that we can become more familiar with a) what they look like, b) how to find the useful bits, and c) demostrate some techniques.
my_var
Error in eval(expr, envir, enclos): object 'my_var' not found
mean[2]
Error in mean[2]: object of type 'closure' is not subsettable
a <- c(one = 1,two = 2, three = 3)
a$one
Error in a$one: $ operator is invalid for atomic vectors
a[[20]]
Error in a[[20]]: subscript out of bounds
read.csv("myfile.csv")
Warning in file(file, "rt"): cannot open file 'myfile.csv': No such
file or directory
Error in file(file, "rt"): cannot open the connection
ggplot()
Error in ggplot(): could not find function "ggplot"
notapackage::notafunction()
Error in loadNamespace(x): there is no package called 'notapackage'
if(NA){
print("was NA")
}
Error in if (NA) {: missing value where TRUE/FALSE needed
And examples of warnings
Warning in if (c(3 > c(1, 2, 3))) {: the condition has length > 1 and
only the first element will be used
[1] "less than three"
Warning in if (c(1, 2, 3) > 3) {: the condition has length > 1 and
only the first element will be used
Warning in mean.default(c("1", "2")): argument is not numeric or
logical: returning NA
[1] NA
As you code and manually test, it can be beneficial to formalise the manual tests into an automated solution so that you can be more efficient and also ensure that you know when you ‘break things’ with future changes. This is particularly useful when you fix bugs in your code, create a test that replicates the condition that caused the bug.
In R one system uses the package testthat
which provides a framework to create these formal tests which will evaluate a piece of code against the known expected output and tell you if they don’t match.
# expect a mean of 2
testthat::expect_equal(mean(c(1,2,3)), 2)