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))