R: Command Line Calculator using Rscript

June 18, 2010

(This article was first published on compBiomeBlog, and kindly contributed to R-bloggers)

I currently use an awesome little bash trick to get a command line calculator that was posted on lifehacker, and that I blogged about previously.

calc(){ awk “BEGIN{ print $* }” ;}

You just add this to your .bashrc file and then you can use it just like calc 2+2. 

This is really useful, however I recently stumbled upon Rscript. This comes with the standard R install and allows you to make a scripts similar to perl or bash with the shebang #!/usr/bin/Rscript, or wherever your Rscript is (you can check with a whereis Rscript command). The nice thing is that it also has a -e option for evaluating an expression at the command line, just like the perl -e for perl one liners. For example:

Rscript -e “round(runif(10,1,100),0)”

[1] 17 23 21 36 10 47 90 81 83  5

This gives you 10 random numbers uniformly distributed between 1 and 100. You can use any R functions this way, even plot for making figures.

Anyway, it seemed that Rscript would be really useful as a command line calculator too. So after a bit of playing and Googling I adapted a nice alias found in a comment on this blog post. Here it is :

alias Calc=’Rscript -e “cat( file=stdout(), eval( parse( text=paste( commandArgs(TRUE), collapse=\”\”))),\”\n\”)”‘

So now you can type things like Calc “-log10(0.05)”, whereas my above mentioned calc would just stare at me blinking, looking a bit embarrassed. You can really go to town if you like:

Calc “round(log2(sqrt(100)/exp(0.05)*(1/factorial(10))),2)”

Calc “plot(hist(rnorm(1E6),br=100))” 

I think I will probably keep the calc version too as it is a bit quicker, with it’s lower overhead, but Calc should be useful for more complex things too.

To leave a comment for the author, please follow the link and comment on their blog: compBiomeBlog.

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...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)