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.
Hi Stew,
ReplyDeleteI am using Rscript to call R within Perl for my bioinformatics project. Is there any way of returning values from the Rscript into the Perl program?
Myra