Abusing the auto print feature of R

10 Jan 2019 - alex

I spend a lot of time on the command line, specifically in the bash shell. Because of this developed muscle memory, I frequently (accidentally) type “exit” in an attempt to quit R.

Unfortunately, I am met by this:

Error : object 'exit' not found

To solve this problem, I decided to insert the following into my .Rprofile

1 2 3 4 5 6 7 print.quitquick <- function ( x , ... ){ base :: q ( "no" ) } exit <- q class ( exit ) <- "quitquick"

How it works

R has a (sometimes confusing) auto print feature in which most objects automatically print a representation of their contents. E.g, vectors and matrices print themselves and objects generated with lm() print some the lm call and the coefficients from the model.

Explanation

Objects use a generic print function that is based on their class. The above code creates a new class called “quitquick”. The print function for this class quits R by calling the built-in q(). In turn, I also create an object called “exit”, to which I assign to the same q() function. Finally, I give the exit object the quitquick class. Now, when I type “exit” [or even “exit()”], the R session will close without prompt. Problem solved!

Unnecessary extra info

Finding out the exact function that runs the when an object is printed (or auto-printed) has always been confusing to me. Usually, viewing the source code for the generic print function of a certain class is found in the print.classname function. However, I found out from reading the documentation in the showMethods function, the generic print function is not always exported from its package. For example, to view the generic print function for the lm class, you would need to look in stats:::print.lm to find the source code.