Skip to content

Instantly share code, notes, and snippets.

@srgorelik
Last active April 11, 2019 16:56
Show Gist options
  • Save srgorelik/fe10476a98be501214a83bac68cfc32d to your computer and use it in GitHub Desktop.
Save srgorelik/fe10476a98be501214a83bac68cfc32d to your computer and use it in GitHub Desktop.
A simple command-line tool for evaluating mathematical expressions.
#!/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)
@srgorelik
Copy link
Author

srgorelik commented Apr 10, 2019

Examples

For help, type:

$ math.R --help

You should see:

Usage: math.R <expression>

Evaluates a mathematical expression.

Arguments:
	<expression>
		A mathematical expression to evaluate (e.g., "5/10")

Options:
	-r INTEGER, --round=INTEGER
		Number of decimal places (default is 2)

	-h, --help
		Show this help message and exit

To evaluate an expression, type:

$ math.R 6/7*100
85.71

By default floats are rounded to two decimal places, but you can change that. For example:

$ math.R 6/7*100 -r 3
85.714

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment