R calculator in Terminal

Until recently, the Mac Calculator app was on my Dock (Mac’s version of a Start menu). It bugged me tremendously that an entire slot was occupied by a program much harder to use than my 15 year-old TI-34 scientific calculator.

TI-34
TI-34: still the better calculator

But before removing Calculator from the Dock, I had to make sure its functionality was covered by another program on the Dock. Chrome was an option—Google Search can do standard arithmetic and trigonometry (example) while Wolfram Alpha can do more and with greater flexibility (example). R is also an option.

But for me, both of these are not ideal. I already struggle with the number of open tabs in my browser and it annoys me to startup the R GUI just to do a quick calculation. Since I always have Terminal open, I instead wrote a quick bash script to run R commands from Terminal:

#/bin/bash

input=$1;

echo "cat($input,\"\n\")" | /usr/bin/R --quiet --vanilla --slave

To run, save to your bin folder, then run as a bash script (will work only for Mac and Linux users). The script takes a single R command as its argument (given in quotes or with special characters escaped). For instance, if you saved the script as c (for calculator), then run:

c "12 * 6"
# returns 72
This entry was posted in Productivity and tagged , , . Bookmark the permalink.

5 Responses to R calculator in Terminal

  1. Jason Hodgson says:

    Just for fun, type the following into your terminal, and then hit enter:

    r

    …pretty neat, huh?

  2. kchiou says:

    But not as satisfying! Also, a slight wait to start up, an annoying welcome message to deal with (unless you add –silent), and you have to hit “q()” right after.

  3. Pingback: R number generation | The Monkey Matters Blog

  4. Jason Hodgson says:

    But with your method you have to start and quit R with every subsequent calculation. …if you really just want a very basic calculator in terminal, there is the Unix application called “basic calculator”. At the terminal type the following:

    bc

    My general approach is to use bc if all I want are a few quick calculations, R in terminal if I want to do things a bit more complicated, and GUI R or Rstudio if I have to learn how to do whatever it is I want to do in R.

  5. kchiou says:

    Awesome! I did not know about bc. That’s really helpful!

Leave a Reply

Your email address will not be published. Required fields are marked *