Stochastic Nonsense

Put something smart here.

Using R

I intend to talk about a bunch of things, mostly involving R, that I had to learn the hard way.  Hopefully this will not only serve as a set of notes for me but help someone else out along the way.

So, say you are running R in the interpreter on either Windows or Mac.  You have some loop that you are waiting for and want to output status messages while you’re waiting.  eg:

`

for( i in 1:10000 ){
  # do something slow
  if( i % 100 == 0 ){ print( paste('at', i ) ); }
}

`

Unfortunately, nothing will show up until the loop is over. The secret is to flush the output buffer: `

logger <- function(str){
  print(str);
  flush.console();
};

`

Unfortunately, this doesn’t quite work yet: `

> logger2 <- function(str){
+   print(paste(str))
+   flush.console()
+ }
> logger2('as')
[1] "as"
NULL
> 

`

The problem is that flush.console is returning NULL and since that is the last value in logger, logger returns NULL. The fix is to return the string so that your function is composable, but prevent annoying textual output in the interpreter by using invisible. This function also adds a timestamp: `

logger <- function(str){
    print( paste( format(Sys.time(), "%b %d %X"), ': ', str, sep=''))
    flush.console()
    invisible(str)
}
>
> logger('a')
[1] "Jun 29 01:28:14: a"
> 

`