Combining head and tail + fast quitting in R

Posted by

I’ve got a bit of time to kill, so I’ve solved three (small and nerdy) problems that have been bothering me.

First, how to get R to display a nice combination of the head & tail of a dataset; second, how to quit R without being asked if I want to save my work every time; and finally, how to post pretty code in a wordpress blog.

Turns out the latter is trivial.

I just needed to add “[ source code_language = ‘ r ‘ ]”

and “[ / source code ]”

without the white spaces, except with a space where I’ve put the `_`

There are lots more options – see the link – I’m going to choose to turn off the default wraplines option.

So I’m using “[ source code_language = ‘ r ‘_wraplines = ‘false’ ]” (same deal with the white space and `_`) to make the following work.

Now for the code.

1/ the head-tail trick:

ht <- function(d, n=5){
  # print the head and tail together
  cat(" head -->  ", head(d,n), "\n", "--------", "\n", "tail -->  ", tail(d,n), "\n")

2/ fast(r)-quit:

The objective here is to get rid of the annoying save question when I issue the `q()` command – so I can quit like an :q! in vim. You probably want to put this in your .Rprofile so it boots with the R session.

If you don’t have an .Rprofiile, just create one and add:

`qq` <- function (save="no", ...) {
  quit(save=save, ...)

You could also add the ht() function to your .Rprofile file – though for both functions, be aware that if you:


You’ll kill them dead.

To make them durable, we need to load them into their own namepspace, as a package which we grab on boot.

That step is for a later post — building an R package is worth doing on its own.


One comment

Comments are closed.