Skip to content

Instantly share code, notes, and snippets.

@russHyde
Created April 22, 2020 15:26
Show Gist options
  • Save russHyde/daefa6a2a321346d1138eec0ed9827db to your computer and use it in GitHub Desktop.
Save russHyde/daefa6a2a321346d1138eec0ed9827db to your computer and use it in GitHub Desktop.
R {optparse} using trailing arguments
# My rscript template assumes all command line arguments are in option-form
# `Rscript <script_name> --logical_option --some_flag some_value --some_other_flag some_other_value`
#
# When you want to pass a variable number of files into your script, the option-form doesn't work well
# so it's better to use trailing arguments
# `Rscript <script_name> --some_option --flag with_value trailing1 trailing2 trailing3 ...`
#
# optparse works well in the latter case:
library(magrittr)
library(optparse)
define_parser <- function() {
description <- "Describe my script"
parser <- OptionParser(
usage = "%prog [options] files", description = description
) %>%
add_option("--some_option", action = "store_true", default = FALSE) %>%
add_option("--flag", type = "double")
parser
}
####
main <- function(opt) {
options <- opt[["options"]]
files <- opt[["args"]]
run_script(
input_files = files,
use_option = options[["some_option"]],
flag_value = options[["flag"]]
)
}
####
test <- function() {
# define tests
}
####
opt <- optparse::parse_args(define_parser(), positional_arguments = TRUE)
if (opt[["options"]][["test"]]) {
test()
} else {
main(opt)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment