I’m about to show you an R trick. Various readers may find it cool, useful and interesting, or stupid, useless and an evil deed undermining the sanctity of R’s functional programming nature (“All bow”). But I hope many of you will find the material here rather intriguing if not useful.
All this involves a trick one can employ while working in R’s top level from interactive mode, the familiar > prompt.
I’ll use as an toy example here. Let’s say I have some counting variable x that I need to increment occasionally as I work. Of course, the straightforward way to do this is
But to save typing and reduce distraction from my main thought processes, it would be nice if I were able to simply typeix
Of course, the straightforward way to do this would be to define a function ix() (“increment x”),ix
and then call it each time by typingix()
But again, I want to save typing, and don’t want to type the parentheses. How can I arrange this?
My approach here will be to exploit the fact that in R’s interactive mode, typing an expression will print the value of that expression. If I type, sayy
R will first determine the class of y, and invoke the print method for that class. If I write that method myself, I can put any R code in there that I wish, such as code to increment x above! So here goes:> w class(w) print.ix x w > x  89 > w > x  90
I set up an S3 class ‘ix’, including a print method print.ix(). I created w, an instance of that class, and as you can see, each time I typed ‘w’, x did get incremented by 1.
What just happened? When I type ‘w’, the R interpreter will know that I want to print that variable. The interpreter finds that w is of class ‘ix’, so it calls the print method for that class, print.ix(), which actually doesn’t do any printing; it merely increments x, as desired.
So I don’t even need to type out even the 4 characters ‘ix()’, or even the 2 characters ‘ix’; just typing the single character ‘w’ suffices. A small thing, maybe, but very useful to me when, in the frenzy of code development and especially debugging, I am able to keep distractions from my train of thought to a minimum.
By the way, we have been doing further development on our polyreg package, with some interesting new features. More news on that soon.
Source link https://www.r-bloggers.com/what-no-parentheses/