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) 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.
Try:
cat(“cat messes up my command prompt position”, fill=TRUE)
Point taken, although “, fill=TRUE” is *lots of typing* compared to “n”. It’s good to be lazy.
https://4dpiecharts.com/2011/01/03/my-new-years-resolution-be-lazier/
0.The code parts of the blog are licensed under the WTFPL v2.?
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.