rdebugging

conditionally debug inside a lapply loop in R


I want to use the trace function to debug a function that contains a loop with lapply. I want to print out x, but only when parameter == 'second'.

I'm not sure what value the parameter at should have when calling trace. The body function can help get which value at should have normally, but this doesn't work for going inside the sapply loop.

f = \(parameters) {
  lapply(parameters, \(parameter) {
    x = data.frame(parameter = parameter, value = 1)
  })
}
f(c("first", "second", "third"))

I'm also interested in finding out how to put a conditional breakpoint in loops like this.


Solution

  • Run this and the source will pop up in an editor.

    trace(f, edit = TRUE)
    

    Then edit the source to add the print or browser statement so that it looks like this and then exit the editor saving the edited version and run f as shown in question. (print(f, useSource = FALSE) will show both original and trace version and untrace(f) will undo it.)

    function (parameters) 
    {
        lapply(parameters, function(parameter) {
            x = data.frame(parameter = parameter, value = 1)
            if (parameter == "second") 
                print(x) # or browser()
            x
        })
    
    }