If your only problem is passing command line arguments to a script in Rstudio, you can use the following trick.
Your script probably accesses the command line arguments with something like:
args <- commandArgs(trailingOnly = TRUE)
After which args
contains a character vector with all the trailing command arguments, which in your example would be c("x", "y", "z")
.
The trick to make your code run in Rstudio without any changes is simply to define a local function commandArgs
that simulates the arguments you want. Here I also take care of the case where trailingOnly = TRUE
although it's rarely used in practice.
commandArgs <- function(trailingOnly = FALSE) {
if (trailingOnly) {
c("x", "y", "z")
} else {
c("Rscript", "--file=prog.R", "--args", "x", "y", "z")
}
}
Once commandArgs
is defined in the global environment, you can run your script in Rstudio and it will see "x", "y", "z"
as its arguments.
You can even go one step further and streamline the process a bit:
#' Source a file with simulated command line arguments
#' @param file Path to R file
#' @param args Character vector of arguments
source_with_args <- function(file, args = character(0)) {
commandArgs <- function(trailingOnly = FALSE) {
if (trailingOnly) {
args
} else if (length(args)) {
c("Rscript", paste0("--file=", file), "--args", args)
} else {
c("Rscript", paste0("--file=", file))
}
}
# Note `local = TRUE` to make sure the script sees
# the local `commandArgs` function defined just above.
source(file, local = TRUE)
}
Let's imagine you want to run the following script:
# This is the content of test.R
# It simply prints the arguments it received.
args <- commandArgs(trailingOnly = TRUE)
cat("Received ", length(args), "arguments:\n")
for (a in args) {
cat("- ", a, "\n")
}
This is the result with Rscript:
$ Rscript --vanilla path/to/test.R x y z
Received 3 arguments:
- x
- y
- z
And you can run the following in R or Rstudio:
source_with_args("path/to/test.R")
#> Received 0 arguments:
source_with_args("path/to/test.R", "x")
#> Received 1 arguments:
#> - x
source_with_args("path/to/test.R", c("x", "y", "z"))
#> Received 3 arguments:
#> - x
#> - y
#> - z