Rython Tips and Tricks – Snippets

Articles From: Eran Raviv
Website: Eran Raviv

The article “Rython Tips and Tricks – Snippets” first appeared on Eran Raviv’s blog.

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. In this post I share 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 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.

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, please

Indeed. Say you want to add an argument to a function you wrote. The argument is for whether you would like to have the execution time reported or not. Call it report_elapsed. Like so:

my_sum <- function(x){
  sum(x)
   Sys.sleep(1)
}
# Add the report_elapsed argument 
my_sum <- function(x, report_elapsed= F){
  ptm <- proc.time()
  out <- sum(x)
  Sys.sleep(1)
  if(report_elapse) {
    cat(prettyNum( (proc.time() - ptm)[3]/60, digits=5), "mins", "\n")  
    }
  out
}
my_sum(rnorm(100), report_elapsed= T)
0.016833 mins 
[1] 6.56

What you can do is to create the snippet timeit:

snippet timeit
 ptm <- proc.time()
 ${1: #your function}
 if(report_elapse) {
 cat(prettyNum( (proc.time() - ptm)[3]/60, digits=5), "mins", "\n") 
 }

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

Can I do in Python?

Why not. The snippet is

snippet timeit
 tic = time.perf_counter()
 ${1: # your function }
          if report_elapsed:
   print("{:.3f}".format(time.perf_counter() - tic), "seconds")

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

def my_sum(x, report_elapsed= False):
      tic = time.perf_counter()
      out= sum(x)
      time.sleep(0.2)
      if report_elapsed:
        print("{:.3f}".format(time.perf_counter() - tic), "seconds") 
      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.

Leave a Reply

Note that all comments are held for moderation before publishing.

Disclosure: Interactive Brokers

Information posted on IBKR Campus that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from Eran Raviv and is being posted with permission from Eran Raviv. The views expressed in this material are solely those of the author and/or Eran Raviv and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

In accordance with EU regulation: The statements in this document shall not be considered as an objective or independent explanation of the matters. Please note that this document (a) has not been prepared in accordance with legal requirements designed to promote the independence of investment research, and (b) is not subject to any prohibition on dealing ahead of the dissemination or publication of investment research.

Any trading symbols displayed are for illustrative purposes only and are not intended to portray recommendations.