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

x 

But to save typing and reduce distraction from my main thought processes, it would be nice if I were able to simply type

ix

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 typing

ix()

But again, I want to save typing, and don’t want to type the . 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, say

y

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
[1] 89
> w
> x
[1] 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.

To leave a comment for the author, please follow the link and comment on their blog: Mad (Data) Scientist.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...


If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...





Source link https://www.r-bloggers.com/what-no-parentheses/

LEAVE A REPLY

Please enter your comment!
Please enter your name here