parse_arguments

library(W4MRUtils)

R script command line

Rscript my_script.R --a-integer 42 --a-float 3.14 --a-boolean FALSE --a-list 1,2,3

Parse those parameters in the R script

param_printer <- function(name, args) {
  sprintf(
    "%s[%s] %s",
    name,
    class(args[[name]])[1],
    paste(args[[name]], collapse = " ")
  )
}
args <- W4MRUtils::parse_args(commandArgs())
#> Warning in W4MRUtils::parse_args(commandArgs()): Please, use the 'optparse'
#> library instead of the 'parse_args' function.
args
#> $`a-integer`
#> [1] 42
#> 
#> $`a-float`
#> [1] 3.14
#> 
#> $`a-boolean`
#> [1] FALSE
#> 
#> $`a-list`
#> [1] "1,2,3"
param_printer("a-integer", args)
#> [1] "a-integer[numeric] 42"
param_printer("a-float", args)
#> [1] "a-float[numeric] 3.14"
param_printer("a-boolean", args)
#> [1] "a-boolean[logical] FALSE"
param_printer("a-list", args)
#> [1] "a-list[character] 1,2,3"
args$`a-list` <- as.numeric(strsplit(args$`a-list`, ",")[[1]])
param_printer("a-list", args)
#> [1] "a-list[numeric] 1 2 3"

Keep original strings

param_printer <- function(name, args) {
  sprintf(
    "%s[%s] %s",
    name,
    class(args[[name]])[1],
    paste(args[[name]], collapse = " ")
  )
}
args <- W4MRUtils::parse_args(
  commandArgs(),
  convert_booleans = FALSE,
  convert_numerics = FALSE
)
#> Warning in W4MRUtils::parse_args(commandArgs(), convert_booleans = FALSE, :
#> Please, use the 'optparse' library instead of the 'parse_args' function.
args
#> $`a-integer`
#> [1] "42"
#> 
#> $`a-float`
#> [1] "3.14"
#> 
#> $`a-boolean`
#> [1] "FALSE"
#> 
#> $`a-list`
#> [1] "1,2,3"
param_printer("a-integer", args)
#> [1] "a-integer[character] 42"
param_printer("a-float", args)
#> [1] "a-float[character] 3.14"
param_printer("a-boolean", args)
#> [1] "a-boolean[character] FALSE"
param_printer("a-list", args)
#> [1] "a-list[character] 1,2,3"