Home > R > Bad kitty!

Bad kitty!

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)

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.

Tags: ,
  1. Margo
    21st January, 2011 at 7:40 am


    cat(“cat messes up my command prompt position”, fill=TRUE)

  2. 27th January, 2011 at 4:34 am

    0.The code parts of the blog are licensed under the WTFPL v2.?

    • 28th January, 2011 at 15:28 pm

      That means “do whatever you want with my code”. If you want to credit me, that would be lovely (but it isn’t compulsory). I use this license because I have no inclination to chase people for misusing my code. Under this license it is impossible to misuse it, hence no problem.

  1. 11th May, 2011 at 9:29 am

Leave a Reply to ????????????? ?????????? Cancel 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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: