Bad kitty!

January 20, 2011
By

(This article was first published on 4D Pie Charts » R, and kindly contributed to R-bloggers)

The cat function bugs me a little. There are two quirks in particular that I find irritating on occasions that I use it.

Firstly, almost everything that I want displayed onscreen, I want on its own line.

> cat("cat messes up my command prompt position")
cat messes up my command prompt position>

So it would be really nice if the function appended a newline to the things I input. Sure, I can manually add the newline, but it looks ugly, and I shouldn’t have to mix formatting with content. Fortunately, the fix is simple.

catn <- function(...) cat(..., "n")
catn("Yes, I would like this content on its own line.")

Feel free to name the improved cat something more exciting, like tiger.

My second bugbear is the inability for cat to take sprintf style arguments. Again, this is easily fixed.

cats <- function(..., file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE)
{
  cat(sprintf(...), file = file, sep = sep, fill = fill, labels = labels, append = append)
}
#Or, combining the two ideas
catsn <- function(...) catn(cats(...))
catsn("The temperature is %g Celcius in %s", -4, "Buxton")

Another tiny problem solved! Before you go using these lovely cat variations, it’s important to discuss when they should be used. Some functions use cat to display progress messages or similar information to the user. This is bad form: if you want to send the user a message then use the message function instead. (This gives you a newline automatically.) The important thing about the message function is that it can be turned off. Compare, e.g.,

count <- function(n) for(i in seq_len(n)) message(i)
count(4)
suppressMessages(count(4))

cat on the other hand should only be used inside print functions (where the user has explicitly requested content onscreen) or in cases where you need to tell the user something.


Tagged: cat, r

To leave a comment for the author, please follow the link and comment on his blog: 4D Pie Charts » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: ,

Comments are closed.