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
.
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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
:
1 2 3 4 5 6 7 8 |
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 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
1 2 3 4 5 6 7 |
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)
):
1 2 3 4 5 6 7 8 9 |
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.
97 Things Every Programmer Should Know
One comment on “Rython tips and tricks – Snippets”