Werden wir Helden für einen Tag

Home | About | Archive

Week 3: Shell aliasing for R programmers

Posted on Dec 23, 2018 by Chung-hong Chan


I use RStudio very rarely. I think the major reason for me to stick with emacs is that I can have a relatively consistent working environment, being it on a desktop or on a server, for the development of all languages (R, Ruby, Python, C++, …). This stickiness to emacs makes me a weirdo sometimes because the new generation R programmers are using RStudio exclusively. When I need to give a demo for example, I need to decide whether to use emacs/ESS or RStudio. Having said that, RStudio is an impressive working environment. The reason for me not to use it, as I said, has nothing to do with its features or ‘weaknesses’.

One impressive feature of RStudio is its close integration with R packages. For example, it has a really nice interface to devtools so that one can click a button to run devtools::document().

I can actually implement similar features with elisp so that I can use them in emacs/ESS. 1 But my way of R development is quite weird. I like to have an interactive R session and an UNIX shell running side-by-side. I usually switching between the R session and the shell to work with different things.

Because of this way of working, I have customized my shell such that it can help me with my R development. For example, there are many R functions we run them for the side-effect. devtools::document() is a great example. For these R operations, they are ideal to be converted into aliases.

As a background, there are actually two ways 2 to execute R commands from shell.

R -e "mean(c(1, 2, 3, 4))"
Rscript -e "mean(c(1, 2, 3, 4))"

You may test the different between the two, but you can quickly find out Rscript is the preferred way.

In my shell, I created an alias to Rscript -e and put it in my .zshrc. So that I can save some typing.

alias rr="Rscript -e"

In my .zshrc, I have the following aliases to launch devtools operations.

alias rdoc='rr "devtools::document()"'
alias rcheck='rr "devtools::check()"'
alias rtest='rr "devtools::test()"'
alias rpkg='rr -e 'devtoos::test(); devtools::document(); devtools::install()'

It is also possible to write functions to parameterize R-related operations. For example, rendering an RMarkdown document or installing an R package from CRAN.

function rmd() {
	rr "rmarkdown::render('$1')"
function cran() {
	rr "install.packages('$1')"

These shell functions can be launched with

rmd my_rmd_file.rmd
cran rio

Another example is a shell function to convert data file

function rio() {
	rr "rio::convert('$1', '$2')"

And launch with

rio mydata.csv mydata.xlsx

Shell customization is addictive and fun. Although this video is about Ruby, many principles also apply to R.

3 down, 49 to go.

  1. Or use the one that has been implemented. 

  2. Or three, if we consider also litter. 

Powered by Jekyll and profdr theme