18

I want to use RStudio to edit an R-script having command line parameters, e.g.,

my_rscript --dataset mydataset

and then to read the optiion value into an R variable, say, dataset, e.g., using optparse library.

However, I could not find where acommand line can be provided in RStudio, so that I could use "Source on save" feature. Instead, I have to hardcode all program parameters in the program itself:

dataset <- "mydataset"

which requires modifying the script text each time I need to specify different data.

Does anybody know how to provide a command line information?

TARehman
  • 6,659
  • 3
  • 33
  • 60
Dmitry K.
  • 1,145
  • 1
  • 9
  • 16
  • Your question didn't seem to be specifically related to RStudio, but more generally to R, so I retagged it. If this isn't what you mean, then you should edit your question. – TARehman Feb 26 '13 at 15:14

7 Answers7

16

For now I do it this way: Open a new window of editing new Rscript. If I want to keep it I can save and name it something like: test_myscript.R This is the content of test_myscript.R:

debug(getopt) # suppose I want to debug 'getopt' function in 'myscript.R'
system("myscript.R -a -b -c")
# Debug process start after this. 
# Check ?browser for help about navigating inside browser
biocyberman
  • 5,675
  • 8
  • 38
  • 50
9

I know this question is old and the link below is old, but it answers the question. No, it's not possible (or wasn't as of Jan 29, 2012) to access command line arguments from RStudio.

Link https://support.rstudio.com/hc/communities/public/questions/200659066-Accessing-command-line-options-in-RStudio?locale=en-us

edi9999
  • 19,701
  • 13
  • 88
  • 127
rrs
  • 9,615
  • 4
  • 28
  • 38
  • 7
    This may be technically correct, but it's obviously possible (and always had been possible) to pass arguments via `system("rscript myscript.r -a -b -c")` which one can execute from RStudio console - see answer from @biocyberman, I think that should be the accepted answer – andreister Sep 11 '14 at 07:53
  • Yes, this is possible, and this should no longer be the accepted answer. commandArgs does this. – Daniel Jul 16 '19 at 15:47
  • 1
    Link is dead, unsurprisingly. – Armen Michaeli Apr 24 '20 at 12:19
6

You can call your programs using Rscript programname.r arg1 arg2 arg3. The arguments are passed to commandArgs, so the following would be true:

Rscript programname.r F N 32

> args <- commandArgs(trailingOnly=TRUE)
> args[1]
[1] F
> args[2]
[1] N
> args[3]
[1] 32
TARehman
  • 6,659
  • 3
  • 33
  • 60
2

This worked for me: My Rscript is as follows:

args <- commandArgs()
print(paste0("args:", args))
print(paste0("args[1]:",args[1]))
print(paste0("args[2]:",args[2]))
print(paste0("args[3]:",args[3]))
print(paste0("# of args:",length(args)))

'

To emulate the command line input I would use with Rscript, I entered this in RStudio:

commandArgs <- function() c("AMZN", 10, 200)

which gave the desired result:

[1] "args:AMZN" "args:10"   "args:200" 
[1] "args[1]:AMZN"
[1] "args[2]:10"
[1] "args[3]:200"
[1] "# of args:3"
upatnite2
  • 21
  • 1
2

If you're interested in using e.g. argparser and continue developing/analyzing interactively using Rstudio, you can use the following work-around:

  1. Write your command line parser in my_rscript and create an object args that contains all parsed input.
  2. Add a line that saves args object to file.
  3. Run my_rscript from command line and specify arguments of interest.
  4. Load the args object from file in Rstudio and continue interactively

Example:

library("argparser")
parser <- arg_parser(description='Process commandline arguments')
parser <- add_argument(parser, arg="--dataset", type="character", help = "Dataset argument")
args = parse_args(parser)
args_file = "tempArgObjectFile.rds"
saveRDS(args, args_file); print(args); quit(); #comment this after creating args_file
args = readRDS(args_file)  #use this to load during interactive development
knish
  • 21
  • 3
1

While this behavior still isn't built into Rstudio, there are a couple of ways you can accomplish something that should help you achieve the workflow you're looking for.

1. Interactive Prompts

The readline and menu functions allow you to make your script interactive by adding prompts into the terminal and accepting input in response. So if your main concern is not wanting to modify your script every time you run it in Rstudio, you can set up a series of these commands to input your arguments every time, like so:

x <- readline("What is your quest? ")
y <- menu(title = "What is your favorite color?", choices = c("Blue", "Clear"))

print(paste("Your quest is", x))
if (y == 1) print("Aaaaaargh!")

2. Detecting interactive mode

A related problem is wanting to be able to change the arguments to the script while working in Rstudio, but without preventing the script from being used on the command line. This is the issue with hard-coding arguments in your script. While replacing or overriding commandArgs makes it easier to just provide all your arguments in one place which can be commented out when it's time for the finished code to be used, this still doesn't solve the problem. Instead, consider detecting whether you're in interactive mode and handling arguments accordingly:

if (interactive()) {
  opts <- c('grail')
} else {
  opts <- commandArgs(trailingOnly = TRUE)
}

print(paste("I seek the", opts[1]))

3. Using the defaults for optparse

If you're using optparse it gets even easier. Just set the default argument in each call to make_option, and this will be what is used when you run the program interactively. This can also be combined with either of the above workflows.

library(optparse)
opt_list <- list(make_option(
    c("--quest"),
    dest = 'your_quest',
    type = 'character',
    default = "the grail"
))

opt_parser <- OptionParser(option_list = opt_list)
opt <- parse_args(opt_parser)

print(paste("You seek", opt$your_quest))
Empiromancer
  • 3,778
  • 1
  • 22
  • 53
0

This is really old but I stumbled across it when trying to do the same thing and I've ended up just trying the following, and is nice and quick if people want to try it (probably only useful for commands that have a couple of easy args though):

Given my Rscript which currently starts:

args <- commandArgs(TRUE)
df <- read.csv(args[1], sep=",", check.names=FALSE, row.names = 1)
.
. # Do some analysis and plotting etc.
.

If I wanted to emulate the command line that the Rscript would otherwise receive, you can make the args vector up 'manually':

args <- c("/path/to/my/inputfile.csv")

then args[1] takes on the same value it always would have. and I simply run everything else in the script by highlighting and executing in RStudio.

Joe Healey
  • 1,232
  • 3
  • 15
  • 34
  • How do you set `args` outside of the script in a way that `args <- commandArgs(TRUE)` inside the script does not override them? – U. Windl Jun 13 '17 at 08:33
  • @U.Windl frankly you can't. This answer doesn't answer the question as written, although it may be useful to people who find the question in future. – Jamie S Oct 24 '18 at 22:40
  • Yes this was not intended to exactly fit the original OPs aims, but I've found it to be a simple 'hack' which others may find useful later. – Joe Healey Oct 24 '18 at 22:43