aneccodeal aneccodeal - 1 year ago 64
R Question

Is it possible to read commandline arguments when running R interactively?

I've got an R script that I usually run via Rscript but sometimes I'd like to be able to run it interactively in R to play with some of the resulting data - problem is, it tries to read commandline arguments via commandArgs and that doesn't seem to work in the R interactive shell. I'd like to be able to start the R shell with the commandline arguments that I'd normally pass to the script and have it read them when I source my script.

$ R arg1 arg2

R version 3.1.2 (2014-10-31) -- "Pumpkin Helmet"
Copyright (C) 2014 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

> args <- commandArgs(trailingOnly = TRUE)
> args
> source("myscript.R")
... fails because myscript.R depends on args

arg1 and arg2 don't seem to get passed along into the R shell.

Answer Source

If you pass the command line arguments like this: R --args 1 2, then you can access them as follows:

> args = commandArgs(trailingOnly=TRUE)
> args
[1] "1" "2"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download