Last active
April 11, 2019 16:56
-
-
Save srgorelik/fe10476a98be501214a83bac68cfc32d to your computer and use it in GitHub Desktop.
A simple command-line tool for evaluating mathematical expressions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env Rscript | |
suppressPackageStartupMessages(library(optparse)) | |
opt.list <- list( | |
make_option(c('-r','--round'), type = 'integer', default = 2, metavar = 'INTEGER', | |
help = 'Number of decimal places (default is %default)') | |
) | |
opt.parser <- OptionParser(option_list = opt.list, | |
usage = 'usage: %prog <expression>\n', | |
description = paste0('Evaluates a mathematical expression.\n\n', | |
'Arguments:\n', | |
'\t<expression>\n', | |
'\t\tA mathematical expression to evaluate (e.g., \"5/10\")')) | |
arguments <- parse_args(opt.parser, positional_arguments = 1) | |
pos.args <- arguments$args | |
opt.args <- arguments$options | |
math.str <- pos.args[1] | |
n.digits <- opt.args$round | |
result <- round(eval(parse(text = math.str)), n.digits) | |
cat(result, fill = T) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Examples
For help, type:
You should see:
To evaluate an expression, type:
$ math.R 6/7*100
By default floats are rounded to two decimal places, but you can change that. For example:
$ math.R 6/7*100 -r 3