File: example.R

package info (click to toggle)
r-cran-argparse 2.3.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 244 kB
  • sloc: sh: 13; makefile: 2
file content (80 lines) | stat: -rw-r--r-- 2,371 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/env Rscript
# Copyright 2012-2013 Trevor L Davis <trevor.l.davis@gmail.com>
# Copyright 2008 Allen Day
#
#  This file is free software: you may copy, redistribute and/or modify it
#  under the terms of the GNU General Public License as published by the
#  Free Software Foundation, either version 2 of the License, or (at your
#  option) any later version.
#
#  This file is distributed in the hope that it will be useful, but
#  WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
suppressPackageStartupMessages(library("argparse"))

# create parser object
parser <- ArgumentParser()

# specify our desired options
# by default ArgumentParser will add an help option
parser$add_argument(
	"-v",
	"--verbose",
	action = "store_true",
	default = TRUE,
	help = "Print extra output [default]"
)
parser$add_argument(
	"-q",
	"--quietly",
	action = "store_false",
	dest = "verbose",
	help = "Print little output"
)
parser$add_argument(
	"-c",
	"--count",
	type = "integer",
	default = 5,
	help = "Number of random normals to generate [default %(default)s]",
	metavar = "number"
)
parser$add_argument(
	"--generator",
	default = "rnorm",
	help = "Function to generate random deviates [default \"%(default)s\"]"
)
parser$add_argument(
	"--mean",
	default = 0,
	type = "double",
	help = "Mean if generator == \"rnorm\" [default %(default)s]"
)
parser$add_argument(
	"--sd",
	default = 1,
	type = "double",
	metavar = "standard deviation",
	help = "Standard deviation if generator == \"rnorm\" [default %(default)s]"
)

# get command line options, if help option encountered print help and exit,
# otherwise if options not found on command line then set defaults,
args <- parser$parse_args()

# print some progress messages to stderr if "quietly" wasn't requested
if (args$verbose) {
	write("writing some verbose output to standard error...\n", stderr())
}

# do some operations based on user input
if (args$generator == "rnorm") {
	cat(paste(rnorm(args$count, mean = args$mean, sd = args$sd), collapse = "\n"))
} else {
	cat(paste(do.call(args$generator, list(args$count)), collapse = "\n"))
}
cat("\n")