How to Debug Your Code in R

Once you have written your code in R, it is important to know how to debug it. To err is human, and programmers fall into that “human” category as well. Nobody manages to write code without errors, so instead of wondering if you have errors in your code, you should ask yourself where you have errors in your code.

Know What to Look For in R

A bug is simply another word for some kind of error in your program. So, debugging doesn’t involve insecticides — it just means getting rid of all type of semantic and/or logical errors in your functions.

Before you start hunting down bugs, you have to know what you’re looking for. In general, you can divide errors in your code into three different categories:

  • Syntax errors: If you write code that R can’t understand, you have syntax errors. Syntax errors always result in an error message and often are caused by misspelling a function or forgetting a bracket.

  • Semantic errors: If you write correct code that doesn’t do what you think it does, you have a semantic error. The code itself is correct, but the outcome of that line of code is not. It may, for example, return another type of object than you expect. If you use that object further on, it won’t be the type you think it is and your code will fail there.

  • Logic errors: Probably the hardest-to-find are errors in the logic of your code. Your code works, it doesn’t generate any error or warning, but it still doesn’t return the result you expect. The mistake is not in the code itself, but in the logic it executes.

This may seem like a small detail, but finding different types of bugs requires different strategies. Often, you can easily locate a syntax error by simply reading the error messages, but semantic errors pose a whole different challenge and logic errors can hide in your code without your being aware they exist.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com