1

when I run a long routine in R, is it possible to show the intermediate steps?

For instance, I'm working with a routine for building randomized versions of an original matrix, based on null models (package bipartite):

#Build N randomized version of the matrix contained in data    
nulls <- nullmodel(data, N=1000, method=3)

#Calculate the same network metric for all N randomized matrices
modules.nulls <- sapply(nulls, computeModules, method = "Beckett")

Depending on the processing power of the computer and the size of N, it takes very long to finish the routine. I would like to include a code to show on the console all intermediate steps for the first and second parts of the routine. Something like "matrix 1, matrix 2... matrix N".

Could you please help me? Thank you!

Marco
  • 347
  • 3
  • 18

1 Answers1

4

1) cat You can add cat, message or print statements to the function.

2) trace or if you don't want to modify the function itself then trace it like this:

# test function
fun <- function(x) length(x) 

trace(fun, quote(print(i <<- i + 1)))

i <- 0
out <- sapply(iris, fun)

giving:

Tracing FUN(X[[i]], ...) on entry 
[1] 1
Tracing FUN(X[[i]], ...) on entry 
[1] 2
Tracing FUN(X[[i]], ...) on entry 
[1] 3
Tracing FUN(X[[i]], ...) on entry 
[1] 4
Tracing FUN(X[[i]], ...) on entry 
[1] 5

To reverse this use untrace(fun) .

3) wrapper Another possibility is to create a wrapper. The flush.console is optional and has the effect of avoiding the console buffering so you see the output immediately.

wrap_fun <- function(x) { print(i <<- i + 1); flush.console(); fun(x) }

i <- 0
out <- sapply(iris, wrap_fun)

4) tkProgressBar A somewhat fancier approach is to use a progress bar. This sample code uses the tcltk package which is included out-of-the-box in all standard R distributions (so you don't need to download and install it -- it's already there and the library statement is sufficient to load it).

library(tcltk)

fun2 <- function(x) Sys.sleep(2) # test function
wrap_fun2 <- function(x) {
   i <<- i + 1
   setTkProgressBar(bar, i, label=i)
   fun2(x)
}

bar <- tkProgressBar("Progress", max = 5)
i <- 0
out <- sapply(iris, wrap_fun2)
close(bar)

Also see ?txtProgressBar and ?winProgressBar (windows only) and also the progress package for other progress bars available.

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Dear Grothendieck, thank you very much for the reply. However, I tried using the codes you suggested, but it didn't work. I'm using two functions (nullmodel and computeModules) that are built in an R package (bipartite), so I cannot modify it. If I use the first solution suggested (trace), how can I fit my script in it? Thank you. – Marco Apr 06 '17 at 17:48
  • You can trace functions in packages. There is even an example in the `trace` help file. – G. Grothendieck Apr 07 '17 at 13:41
  • Thank you. I've already read this help, but did not find the solution. I'll look again. – Marco Apr 17 '17 at 17:59