Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make R's output more verbose so as to reassure me that it hasn't broken yet?

I often run code that eats up a lot of RAM, and may take as much as an hour before it gives its outputs. Often, I'll be half an hour in to running such code and I'll be worrying that something gone wrong. Is there any way that I can get R to reassure me that there's not been any errors yet? I suppose that I could put milestones in to the code itself, but I'm wondering if there's anything in R (or RStudio) that can automatically do this job at run time. For example, it would be handy to see how much memory the code is using, because then I'd be reassured that it's still working whenever I see the memory use significantly vary.

like image 949
J. Mini Avatar asked Apr 22 '20 16:04

J. Mini


2 Answers

You might like my package {boomer}.

If you rig() your function, all its calls will be exploded and printed as the code is executed.

For instance

# remotes::install_github("moodymudskipper/boomer")
fun <- function(x) {
  x <- x + 1
  Sys.sleep(3)
  x + 1
}

library(boomer)

# rig() the function and all the calls will be exploded
# and displayed as they're run
rig(fun)(2)

example

like image 144
Moody_Mudskipper Avatar answered Oct 05 '22 23:10

Moody_Mudskipper


One way is:

  1. to make a standalone file containing all the stuff to be run,
  2. sourcing it and getting warned when the code is done, possibly with error.

The small function warn_me below:

  • runs the source file located in "path"
  • possibly catches an error, if an error there was
  • plays a sound when the run is over
  • sends an email reporting the status of the run: OK or fail
  • optionally: plays a sound until you stop it, so you can't miss it's over

And here it is:

warn_me = function(path, annoying = FALSE){
    # The run
    info = try(source(path))
    
    # Sound telling it's over
    library(beepr)
    beep()
    
    # Send an email with status
    library(mailR)
    msg = if(inherits(info, "try-error")) "The run failed" else "It's over, all went well"
    
    send.mail(from = "[email protected]",
              to = "[email protected]",
              subject = msg,
              body = "All is in the title.",
              smtp = list(host.name = "smtp.mailtrap.io", port = 25,
                          user.name = "********",
                          passwd = "******", ssl = TRUE),
              authenticate = TRUE,
              send = TRUE)
    
    if(annoying){
        while(TRUE){
            beepr::beep()
            Sys.sleep(1)
        }
    }
}

warn_me(path)

I didn't test the package mailR myself, but any email sending package would do. See this excellent page on sending emails in R for alternatives.

like image 26
Laurent Bergé Avatar answered Oct 06 '22 01:10

Laurent Bergé