R: Command Line Calculator using Rscript
[This article was first published on compBiomeBlog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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.Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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 about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.