One approach to debugging is to include print statements at various places to make sure your code has reached those points and to show current values of variables. Often this is sufficient, but sometimes more sophisticated tools are useful.

Sometimes it is necessary to signal or trap errors in R.

Once code is running you may want to see if you can make it run faster. Profiling can help.