Skip to content

Instantly share code, notes, and snippets.

@russHyde
Created April 22, 2020 15:26
Show Gist options
  • Select an option

  • Save russHyde/daefa6a2a321346d1138eec0ed9827db to your computer and use it in GitHub Desktop.

Select an option

Save russHyde/daefa6a2a321346d1138eec0ed9827db to your computer and use it in GitHub Desktop.

Revisions

  1. russHyde created this gist Apr 22, 2020.
    51 changes: 51 additions & 0 deletions optparse_with_trailing_args.R
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    # 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)
    }