Skip to content

Instantly share code, notes, and snippets.

@dtenenba
Last active December 19, 2015 19:09
Show Gist options
  • Save dtenenba/6004179 to your computer and use it in GitHub Desktop.
Save dtenenba/6004179 to your computer and use it in GitHub Desktop.
# print() is the simplest debugging technique
myFunction <- function()
{
#...possibly buggy code...
print("here i am")
#...more possibly buggy code...
print("here i am 2")
}
# a buggy function
buggyFunc <- function()
{
for (i in 1:2)
{
if (i == 2)
stop("Pretend I am a bug.")
}
}
# traceback() - where was the last error?
buggyFunc()
traceback()
# debug() - interactive debugging
debug(buggyFunc)
buggyFunc()
?debug
undebug(buggyFunc)
# debug tip #1 - debugging a nested function
buggyFunc2 <- function()
{
nestedBuggyFunction <- function()
{
stop("Pretend I am a bug")
}
nestedBuggyFunction()
}
debug(nestedBuggyFunction)
debug(buggyFunc2)
buggyFunc2()
# debug tip #2 - debugging a method
library(GenomicRanges)
example(GRanges)
x <- selectMethod("seqinfo", "GRanges")
debug(x)
seqinfo(gr)
# browser()
browserDemo <- function()
{
browser()
}
browserDemo()
# trace - in its simplest form, just prints out a line when a function is invoked
trace(sum)
sum(1,2)
trace: sum(1, 2)
untrace(sum) # turn off trace
trace(sum)
sum(1, 3)
# trace, for those hard-to-reach places
buggyFunc3 <- function()
{
for (i in 1:10000)
{
if (i == 7777)
stop("Found a bug!")
}
}
# find R's notion of the line number where the problem occurs
l <- as.list(body(buggyFunc3))
l
as.list(l[[2]])
trace(buggyFunc3, at=list(c(2,4,2,3,2)), tracer=browser)
buggyFunc3()
# conditional trace, if we know a function has trouble with
# certain values
buggyFunc4 <- function(x)
{
if (x >= 10 && x <= 20) stop("I can't deal with x!")
}
trace(buggyFunc4, quote(if (x >= 10 && x <= 20) browser()))
buggyFunc4(14)
buggyFunc4(24)
# a tracer can be anything, not just browser()
trace(buggyFunc4,
quote(if (x >= 10 && x <= 20)
print(sprintf("Tracer says that x is %s", x))))
buggyFunc4(24)
buggyFunc4(14)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment