Home > R > A clock utility, via console hackery

A clock utility, via console hackery

A discussion on StackOverflow today shows an interesting use of special characters inside the cat function.

The most common special characters that you may have come across are the tab and newline characters, represented by \t and \n respectively. Try them for yourself.

cat("Red\tlorry\nYellow\tlorry\n")

cat also respects the backspace character, \b, and the carriage return character, \r, which means that you can delete things. Usually, this isn’t very useful, but it allows us to overwrite text in the console.

cat("ab\bc")      #\b removes the previous character
cat("abc\rde")    #\r removes everything to the start of the line

Here’s a simple clock utility, adapted from Mark, Zach and DWin’s code in the linked question, that uses this technique.

clock <- function(format = "%H:%M:%S", refresh = 1)
{
  repeat
  {
    cat("\r", format(Sys.time(), format), sep = "")
    flush.console()
    Sys.sleep(refresh)
  }
}
clock()
clock("%A %d %B %Y %I:%M:%OS3 %p", 1e-3)

Press escape to exit the clock utility. You can see a complete list of special characters over at asciitable.com.

EDIT: clock function now with customisable formatting.
ANOTHER EDIT: Refresh rate now updateable; extra example.

About these ads
Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 160 other followers

%d bloggers like this: