| Title: | Argument Handling for Command-Line, Stand-Alone R Scripts |
|---|---|
| Description: | Provides functions to handle command-line arguments for R scripting. It enables building stand-alone R programs that accept and parse command-line options in 'BIOS' style. Zhang (2025) <https://github.com/bedapub/ribiosArg>. |
| Authors: | Jitao David Zhang [aut, cre, ctb] (ORCID: <https://orcid.org/0000-0002-3085-0909>), Balazs Banfai [ctb] |
| Maintainer: | Jitao David Zhang <[email protected]> |
| License: | GPL-3 |
| Version: | 1.5.0 |
| Built: | 2026-05-16 08:29:02 UTC |
| Source: | https://github.com/bedapub/ribiosArg |
Get the value of an named argument
argGet(opt, default = NULL, choices = NULL)argGet(opt, default = NULL, choices = NULL)
opt |
name of the argument to be parsed |
default |
default values to be returned if the argument is not provided |
choices |
a character vector of accepted values; if a string outside the vector is provided, the function will stop and print error message |
The parsing is performed at C-level. It is an abbreiviation of argGetPos(opt, ind=1, default=NULL, choices=NULL)
A character string representing the value of the argument
Jitao David Zhang <[email protected]>
argParse, argGetPos, and argPresent
argGet("infile")argGet("infile")
Get the value of an named argument with the given position
argGetPos(opt, ind = 1L, default = NULL, choices = NULL)argGetPos(opt, ind = 1L, default = NULL, choices = NULL)
opt |
name of the argument to be parsed |
ind |
index of the argument to be parsed, starting from 1. |
default |
default values to be returned if the argument is not provided |
choices |
a character vector of accepted values; if a string outside the vector is provided, the function will stop and print error message |
The parsing is performed at C-level. If the argument accepts only one value, users can also call argGet(opt, default=NULL, choices=NULL)
A character string representing the value of the argument
Jitao David Zhang <[email protected]>
argParse, argGet, and argPresent
argGetPos("thresholds", ind=2)argGetPos("thresholds", ind=2)
Check whether the argument parser has been initialized
argIsInit()argIsInit()
Logical, TRUE if argParse has been called, FALSE otherwise.
Parser of command-line parameters in BIOS style
Test whether the given option is present in the command line or not
argParse(optargs, reqargs, usage = paste(scriptName(), "-h"), strict = TRUE) argPresent(opt)argParse(optargs, reqargs, usage = paste(scriptName(), "-h"), strict = TRUE) argPresent(opt)
optargs |
String describing optional arguments. Syntax: |
reqargs |
String describining required arguments. Syntax: |
usage |
A character string to be printed if the command-line option parsing fails |
strict |
Logical, are extra un-prefixed parameters allowed? If set to |
opt |
Character string, option name |
argParse must be called before argGet,argGetPos
, argPresent, or argGetDefault. It checks whether the command line syntax agrees
with the specification of optargs and reqargs. If not,
the usage message is printed and the program exists.
argPresent returns a boolean value indicating whether the option is present or not.
If the syntax was found correct, argGetPos can be called to
fetch the indth value of the option opt (indexing from 1). For instance,
if the following option -ranges 3 5 is defined,
argGetPos(“range”, 2) returns 5. argGet is
a shortcut to fetch the first element. If the opt is missing, the
default value will be returned.
argParse is used for the side effects. If strict is set to
TRUE, an invisible NULL is returned; otherwise, extra
un-prefixed parameters are returned as an invisible character vector
argGet and argGetPos returns a character
string. argPresent returns a boolean value.
In case of any error (wrong syntax, or not-existing option) the R session quits while printing the error message.
argParse("verbose threshold,2", "infile outfile", usage="prog [-infile ]infile [-outfile ]outfile [-verbose] [-threshold MIN MAX]") argIsInit() argPresent("verbose")argParse("verbose threshold,2", "infile outfile", usage="prog [-infile ]infile [-outfile ]outfile [-verbose] [-threshold MIN MAX]") argIsInit() argPresent("verbose")
Test if named arguments exists
existArg(args)existArg(args)
args |
Argument names, without leading minus sign |
Options are those arguments with a leading minus sign (e.g. "-opt"). This function tells whether queried options exist in the argument list.
A vector of logicals, indicating whether the arguments exist
comm <- paste(c("Rscript --vanilla -e", "'", "library(ribiosArg);", "existArg(c(\"opt\", \"opt2\", \"opt3\"))", "'", "-opt abc -opt3"), collapse=" ") system(comm)comm <- paste(c("Rscript --vanilla -e", "'", "library(ribiosArg);", "existArg(c(\"opt\", \"opt2\", \"opt3\"))", "'", "-opt abc -opt3"), collapse=" ") system(comm)
This function is out-dated. Please use argparse instead.
getArg(args, onlyArg = FALSE, missingArg = FALSE)getArg(args, onlyArg = FALSE, missingArg = FALSE)
args |
Character strings, named arguments |
onlyArg |
Any type, What value should be returned if only the option is available and no value has been provided |
missingArg |
Any type, What value should be returned if the option is not available |
Options are those arguments with a leading minus sign. They can
have one or more values following them, which will be taken as the value
of the option. If no such values are availble, user could decide how to
interpret the option by setting the onlyArg parameter. Similarly,
missing options can be handled by missingArg
From version 1.0.3 onlyArg and missingArg accepts NULL as inputs.
A list when more than one option were queried; or a vector if only one option was queried.
Test whether the environment is set for debugging
isDebugging()isDebugging()
A logical value
setDebug and unsetDebug
isDebugging() unsetDebug() isDebugging() setDebug()isDebugging() unsetDebug() isDebugging() setDebug()
Test whether the environment is set for debugging, or it's an interactive session
isIntDebugging()isIntDebugging()
A logical value
Make a factor
makeFactor(groups, levels = NULL, make.names = TRUE, verbose = FALSE)makeFactor(groups, levels = NULL, make.names = TRUE, verbose = FALSE)
groups |
Character strings |
levels |
Character vector, indicating strings |
make.names |
Should names be converted to adhere to the rule of variable names in R |
verbose |
Logical vector |
A factor with the specified levels.
makeFactor(c("A", "B", "C", "C", "A"), levels=LETTERS[3:1]) makeFactor(c("A 1", "B 2", "C 3", "C 3", "A 1"), levels=c("A 1", "C 3", "B 2"), make.names=TRUE) makeFactor(c("A 1", "B 2", "C 3", "C 3", "A 1"), levels=c("A 1", "C 3", "B 2"), make.names=FALSE) makeFactor(c("A 1", "B 2", "C 3", "C 3", "A 1"), levels=c("A 1", "C 3", "B 2"), make.names=FALSE, verbose=TRUE)makeFactor(c("A", "B", "C", "C", "A"), levels=LETTERS[3:1]) makeFactor(c("A 1", "B 2", "C 3", "C 3", "A 1"), levels=c("A 1", "C 3", "B 2"), make.names=TRUE) makeFactor(c("A 1", "B 2", "C 3", "C 3", "A 1"), levels=c("A 1", "C 3", "B 2"), make.names=FALSE) makeFactor(c("A 1", "B 2", "C 3", "C 3", "A 1"), levels=c("A 1", "C 3", "B 2"), make.names=FALSE, verbose=TRUE)
Parse a character string into factor
parseFactor(str, rlevels = NULL, make.names = TRUE, collapse = ",")parseFactor(str, rlevels = NULL, make.names = TRUE, collapse = ",")
str |
A character string giving groups |
rlevels |
A character string giving levels |
make.names |
Logical, should names be converted to adhere to the rule of variable names in R |
collapse |
Character used in |
A factor parsed from the input string with the specified levels.
parseFactor("A,B,C,B,A", rlevels="A,B,C") rgroup <- "A,B,C,D,B,C,A,D,B" rlevels <- "D,A,B,C" parseFactor(rgroup, rlevels) groups <- c("ATest", "Control", "Control", "ATest") levels <- c("Control", "ATest") makeFactor(groups, levels) # if 'groups' is a factor and 'levels' NULL or missing, its levels are respected groups <- factor(c("B", "C", "A", "D"), levels=c("D","C","A","B")) makeFactor(groups) groups <- c("ATest", "Control", "Control", "ATest") levels <- c("Control", "ATest", "Unknown") makeFactor(groups, levels) groups <- c("ATest", "Control", "Control", "ATest", "BTest") levels <- c("Control", "ATest") try(makeFactor(groups, levels))parseFactor("A,B,C,B,A", rlevels="A,B,C") rgroup <- "A,B,C,D,B,C,A,D,B" rlevels <- "D,A,B,C" parseFactor(rgroup, rlevels) groups <- c("ATest", "Control", "Control", "ATest") levels <- c("Control", "ATest") makeFactor(groups, levels) # if 'groups' is a factor and 'levels' NULL or missing, its levels are respected groups <- factor(c("B", "C", "A", "D"), levels=c("D","C","A","B")) makeFactor(groups) groups <- c("ATest", "Control", "Control", "ATest") levels <- c("Control", "ATest", "Unknown") makeFactor(groups, levels) groups <- c("ATest", "Control", "Control", "ATest", "BTest") levels <- c("Control", "ATest") try(makeFactor(groups, levels))
Parse files from command line option, which can be (1) a string vector of files, (2) a file listing input files (e.g. pointer file), (3) a directory, or (4) a zip/tar/gz file (determined by suffix). In the later two cases, file patterns can be specified.
parseFiles( str, sep = ",", pattern = NULL, recursive = TRUE, ignore.case = TRUE )parseFiles( str, sep = ",", pattern = NULL, recursive = TRUE, ignore.case = TRUE )
str |
A character string |
sep |
Seperator used in the string |
pattern |
Pattern string, if given, only files matching the pattern will be returned |
recursive |
In cse of directory or compressed files, whether files should be found recursively |
ignore.case |
In case of directory or compressed files, whether case should be ignored |
A character vector of file paths.
In case of compressed files, a temp dir will be created: the user should take care of cleaning up!
Numeric vectors can be given as arguments in two ways: (1) separated by blanks or (2) separated by other common separators, such as comma (,). This function parses a string, or a string vector into a numeric vector of expected length. In addition it is failure safe: user can specify the return value in case the parsing was not successful,
parseNumVec(str, expLen = 2, failVal = c(5, 5), sep = ",")parseNumVec(str, expLen = 2, failVal = c(5, 5), sep = ",")
str |
A character string |
expLen |
Integer or |
failVal |
If the parsing failed (for example length not correct, or non-numeric values were provided, this value will be returned |
sep |
Separator in the character string, default "," |
The input value mostly comes from return values of the argGet function.
A numeric vector of the parsed values, or failVal if parsing fails.
parseNumVec("3,7,9", expLen=3)parseNumVec("3,7,9", expLen=3)
The function parses parameters in the form of
KEY1=VAL1,KEY2=VAL2,KEY3=VAL3 into data.frame.
parsePairs( str, collapse = ",", sep = "=", colnames = c("key", "value"), trim = TRUE, ... )parsePairs( str, collapse = ",", sep = "=", colnames = c("key", "value"), trim = TRUE, ... )
str |
Character string |
collapse |
Collapse character used in the string |
sep |
Seperator used in the string |
colnames |
Column names of the returned |
trim |
Logical, whether additional spaces should be trimmed |
... |
Further parameters passed to |
If input string is NULL, the function returns NULL. This
can be useful in case the parameter is optional and not specified.
A data.frame containing keys and values
parsePairs("A=3,B=4,C=5", collapse=",", sep="=") parsePairs("A:3|B:4|C:5", collapse="|", sep=":")parsePairs("A=3,B=4,C=5", collapse=",", sep="=") parsePairs("A:3|B:4|C:5", collapse="|", sep=":")
This function parses collapsed multiple options into a vector of
character strings. Each option is optionally trimmed of leading and tailing empty
spaces given by trim. See examples.
parseStrings(str, collapse = ",", trim = TRUE, ...)parseStrings(str, collapse = ",", trim = TRUE, ...)
str |
A character string to be parsed |
collapse |
Character(s) used in the character string to concatenate strings |
trim |
Logical, whether additional spaces should be trimmed |
... |
Further parameters passed to |
In case of multiple separators, they can be given by concatenating
with piple signs, e.g. ,|\t.
If input string is NULL, the function returns NULL. This
can be useful in case the parameter is optional and not specified.
A vector of character strings
parseStrings("veni, vidi, vici") parseStrings("veni, vidi, vici", trim=FALSE) parseStrings("I came, I saw, I conquered") # options are trimmed parseStrings("a,b,\tc,d\n") # it works also with only one option parseStrings("a") # more than one separators parseStrings("a,b,c;d", collapse=",|;")parseStrings("veni, vidi, vici") parseStrings("veni, vidi, vici", trim=FALSE) parseStrings("I came, I saw, I conquered") # options are trimmed parseStrings("a,b,\tc,d\n") # it works also with only one option parseStrings("a") # more than one separators parseStrings("a,b,c;d", collapse=",|;")
ribiosIO ribiosIO provides Command-line argument handling for R scripting
Jitao David Zhang <[email protected]>
This function is called at the beginning of an Rscript, in order to prepare the R environment to run in a script setting.
scriptInit()scriptInit()
No return value, called for side effects.
scriptInit()scriptInit()
Get the file name of the Rscript that is currently being executed. The function is mainly called by stand-alone Rscripts.
scriptName()scriptName()
The name is determined by the --file/-f option in the command line.
When the R session was not initiated by a Rscript (i.e. there is no --file or -f option in the command line), NULL is returned.
Note that the function supports calling Rscript via --file or -f with R. This applies to cases where a Rscript, marked as executable, and is called from the command line.
A character string containing the file name of the Rscript.
Jitao David Zhang <[email protected]>
commandArgs and getArg
scriptName()scriptName()
Get the normalised path of the Rscript that is currently being executed. The function is mainly called by stand-alone Rscripts.
scriptPath()scriptPath()
The name is determined by the --file/-f option in the command line.
When the R session was not initiated by a Rscript (i.e. there is no --file or -f option in the command line), NULL is returned.
Note that the function supports calling Rscript via --file or -f with R. This applies to cases where a Rscript, marked as executable, and is called from the command line.
A character string containing the normalised path of the Rscript.
Jitao David Zhang <[email protected]>
scriptPath()scriptPath()
Generate a Rscript with its skeleton
scriptSkeleton(file)scriptSkeleton(file)
file |
Output file. Use 'file=stdout()' to write the output to standard output. |
Invisibly returns the character vector of skeleton lines.
Called for its side effect of writing to file.
scriptSkeleton(file = file.path(tempdir(), "myscript.R"))scriptSkeleton(file = file.path(tempdir(), "myscript.R"))
Set the enrivonment for debugging
setDebug()setDebug()
A logical value, whether the setting was susccessful or not
Remove the debugging flag of the the enrivonment
unsetDebug()unsetDebug()
A logical value, whether the removal was successful or not
isDebugging and setDebug