Rython tips and tricks – Snippets

R or Python? who cares! Which editor? now that’s a different story.

I like Rstudio for many reasons. Outside the personal, Rstudio allows you to write both R + Python = Rython in the same script. Apart from that, the editor’s level of complexity is well-balanced, not functionality-overkill like some, nor too simplistic like some others. This post shares how to save time with snippets (easy in Rstudio). Snippets save time by reducing the amount of typing required, it’s the most convenient way to program copy-pasting into the machine’s memory.

In addition to the useful built-ins snippets provided by Rstudio like lib or fun for R and imp or def for Python, you can write your own snippets. Below are a couple I wrote myself that you might find helpful. But first we start with how to use snippets.

How to use snippets in Rstudio?

The following two images are pasted here from owenjonesuob.

To get a list of built-in snippets in Rstudio you go to Tools > global Option > code > edit snippet .
Snippets snapshot
The last three snippets are written by the user. You can see what they do here:

So for example if you type hh and SHIFT+TAB, the two lines defined in the snippets are pasted.

Use case?

Indeed. Say you want to add an argument to a function you wrote. The argument is whether to report the execution-time or not. Call it report_elapsed. Like so:

What you can do is to create the snippet timeit:

Add that snippet to your snippet file. Now each time you want to add an execution time argument (report_elapsed) to any function you can use the snippet you wrote to wrap it with the necessary lines. Just type timeit, SHIFT+TAB and paste your function inside.

Can I do in Python?

Why not. The snippet is

and the function is now (after adding the report_elapsed and return(out)):

Footnotes and a couple of good books about coding

As a footnote, I don’t know where I can find a snippet gallery, but that would be good venue to share community snippets.

97 Things Every Programmer Should Know

Coding All-in-One For Dummies

One comment on “Rython tips and tricks – Snippets”

Leave a Reply

Your email address will not be published. Required fields are marked *