customised help function in argparse() in R
1
0
Entering edit mode
Learner • 0
@a923bf09
Last seen 22 months ago
Norway

I have following R script

library(argparse)
library(crayon)

# Define the help message
help_message <- function() {
    cat("\n")
    cat(crayon::bold("Usage:   This is help function\n"))

}

parser <- ArgumentParser()

# Define the command line arguments

parser <- ArgumentParser()
parser$add_argument("-f1", "--file1", dest = "file1")
parser$add_argument("-f2", "--file2", dest = "file2")


args <- parser$parse_args() # Parse the command line arguments


if (is.null(args$file1)) {
  cat(crayon::red("\nERROR: Missing argument -f1/--file1\n"))
  help_message()
  q(status = 1)
}

if (is.null(args$file2)) {
  cat(crayon::red("\nERROR: Missing argument -f2/--file2\n"))
  help_message()
  q(status = 1)
}

When I use Rscript test1.R (without any command line argument), I get output from my customised help_message()

ERROR: Missing argument -f1/--file1

Usage:   This is help function

But when I use Rscript test1.R -h, I get default help function output

usage: test1.R [-h] [-f1 FILE1] [-f2 FILE2]

optional arguments:
  -h, --help            show this help message and exit
  -f1 FILE1, --file1 FILE1
  -f2 FILE2, --file2 FILE2

If I use Rscript test1.R -f1, I get following output

usage: test1.R [-h] [-f1 FILE1] [-f2 FILE2]
test1.R: error: argument -f1/--file1: expected one argument

I want to get output from customised help_message in all the cases.

command-line R command-line-arguments argparse() • 979 views
ADD COMMENT
0
Entering edit mode
@james-w-macdonald-5106
Last seen 1 day ago
United States

This question is off-topic for this support site. Questions about base R should be directed to r-help@r-project.org

ADD COMMENT

Login before adding your answer.

Traffic: 440 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6