Bugs are an inevitable part of programming
Learning to fix them is an art that comes only from practice
(Un)fortunately, upto 90% programming time is debugging
In the event of a bug:
Syntax/run-time errors that cause fatal errors: Easiest to deal with
Logical errors:
R runs without errors, however the output is wrong.
Much harder to track.
Good programming style makes your life easier
Have informative variable/function names
Break your code into smaller functions and test individually.
Much better to build up from a set of bug-free components than to write down a big function and then debug.
Try to read the error message
Can be confusing, but is informative compared to e.g. Latex (gibberish) or C (usually ‘segmentation faults’)
"can’t find the object my_obj"
Have you set variable/loaded package?
Have you set variable/loaded package? A common error:
for(i in 1:10) a[i] <- i # First declare a!
Have you set variable/loaded package? A common error:
ggplot(my_data) + geom_line(aes(x=x,y=y))
"Error: Incompatible lengths ..."
What are the lengths?
missing value where TRUE/FALSE needed
What is the argument to if/ while ?
R always tell you where the error was detected
The actual cause can be much earlier than R indicates.
(In general, bad idea to write many lines of code without checking syntax a few times along)
A Google search often leads to a solution on stackexchange (be sure to remove variable names specific to your code)
(ericlippert.com/2014/03/05/how-to-debug-small-programs/)
For each line know what input and predicted outputs are
While debugging code, intersperse if
’s and print
’s.
if(prob > 1 || prob < 0) {
print ”NOOO!!! Invalid probability”
stop();
}
The stopifnot
functions are also useful:
stopifnot(prob > 0, prob < 1)
If you can’t track it down by inspection or want to email me:
A third person should:
Do not send me your entire code, saying ”Help”
Do not send me just the error message, saying ”Help”
Remove all unnecessary code after error (easy)
Remove all unnecessary code before error (harder):
Most class errors I’ve seen can be reduced to one assignment and one command
A good set of guidelines: http://stackoverflow.com/help/mcve
Write a minimal program:
Ask a specific question
"My code (see attached) gives an error": This is a story, not a question
“Why does my code (see attached) gives an error?”: Unhelpful question deserves unhelpful answer “Maybe your code is wrong”
Asking a specific question is halfway towards fixing your bug
Also convinces me that you thought about it